MapReduceOutput(JacksonDBCollection<?, ?> sourceCollection, com.mongodb.MapReduceOutput output, Class<T> type, Class<K> keyType) { this.output = output; if (output.getOutputCollection() != null) { this.outputCollection = JacksonDBCollection.wrap(output.getOutputCollection(), type, keyType, sourceCollection.getObjectMapper()); this.resultSet = outputCollection.find(); } else { this.outputCollection = null; Collection<T> results = new ArrayList<T>(); for (DBObject result : output.results()) { results.add(sourceCollection.convertFromDbObject(result, type)); } this.resultSet = results; } }
/** * Inserts objects into the database. * if the objects _id is null, one will be generated * you can get the _id that were generated by calling getSavedObjects() or getSavedIds() on the result * * @param list The objects to insert * @return The result * @throws MongoException If an error occurred */ @SuppressWarnings({"unchecked"}) public WriteResult<T, K> insert(List<T> list) throws MongoException { return insert(list.toArray((T[]) new Object[list.size()])); }
/** * renames of this collection to newName * * @param newName new collection name (not a full namespace) * @param dropTarget if a collection with the new name exists, whether or not to drop it * @return the new collection * @throws MongoException If an error occurred */ public JacksonDBCollection<T, K> rename(String newName, boolean dropTarget) throws MongoException { return new JacksonDBCollection<T, K>(dbCollection.rename(newName, dropTarget), type, keyType, objectMapper, features); }
/** * Find an object by the given id * * @param id The id * @return The object * @throws MongoException If an error occurred */ public T findOneById(K id, T fields) throws MongoException { return findOneById(id, convertToBasicDbObject(fields)); }
/** * Performs an update operation. * * @param query search query for old object to update * @param object object with which to update <tt>query</tt> * @param upsert if the database should create the element if it does not exist * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will * not be inserted if it does not exist in the collection and upsert=true and multi=true. * See <a href="http://www.mongodb.org/display/DOCS/Atomic+Operations">http://www.mongodb.org/display/DOCS/Atomic+Operations</a> * @param concern the write concern * @return The write result * @throws MongoException If an error occurred */ public WriteResult<T, K> update(T query, T object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException { return update(convertToBasicDbObject(query), convertToBasicDbObject(object), upsert, multi, concern); }
/** * Finds a collection that is prefixed with this collection's name. * A typical use of this might be * <blockquote><pre> * DBCollection users = mongo.getCollection( "wiki" ).getCollection( "users" ); * </pre></blockquote> * Which is equivalent to * <pre><blockquote> * DBCollection users = mongo.getCollection( "wiki.users" ); * </pre></blockquote> * * @param n the name of the collection to find * @param type The type of the collection * @return the matching collection */ public <S, L> JacksonDBCollection<S, L> getCollection(String n, Class<S> type, Class<L> keyType) { return wrap(getDB().getCollection(getName() + "." + n), type, keyType, objectMapper); }
@Path("bars") @GET @Produces(MediaType.APPLICATION_JSON) public List<Bar> listBars() { return getJacksonDBCollection().find().toArray(); }
/** * Fetch a collection of dbrefs. This is more efficient than fetching one at a time. * * @param collection the collection to fetch * @param fields The fields to retrieve for each of the documents * @return The collection of referenced objcets */ public <R, RK> List<R> fetch(Collection<DBRef<R, RK>> collection, DBObject fields) { Map<JacksonCollectionKey, List<Object>> collectionsToIds = new HashMap<JacksonCollectionKey, List<Object>>(); for (DBRef<R, RK> ref : collection) { if (ref instanceof FetchableDBRef) { JacksonCollectionKey key = ((FetchableDBRef) ref).getCollectionKey(); List<Object> ids = collectionsToIds.get(key); if (ids == null) { ids = new ArrayList<Object>(); collectionsToIds.put(key, ids); } ids.add(getReferenceCollection(key).convertToDbId(ref.getId())); } } List<R> results = new ArrayList<R>(); for (Map.Entry<JacksonCollectionKey, List<Object>> entry : collectionsToIds.entrySet()) { for (R result : this.<R, RK>getReferenceCollection(entry.getKey()).find( new QueryBuilder().put("_id").in(entry.getValue()).get(), fields)) { results.add(result); } } return results; }
private JacksonDBCollection<Bar, String> getJacksonDBCollection() { return JacksonDBCollection.wrap(BarServer.mongoDB.getCollection(Bar.class.getSimpleName().toLowerCase()), Bar.class, String.class); }
/** * Finds the first document in the query and updates it. * * @param query query to match * @param fields fields to be returned * @param sort sort to apply before picking first document * @param remove if true, document found will be removed * @param update update to apply * @param returnNew if true, the updated document is returned, otherwise the old document is returned (or it would be lost forever) * @param upsert do upsert (insert if document not present) * @return the object */ public T findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert) { return convertFromDbObject(dbCollection.findAndModify(serializeFields(query), fields, sort, remove, update, returnNew, upsert)); }
/** * Get a collection for loading a reference of the given type * * @param collectionKey The key for the collection * @return The collection */ public <T, K> JacksonDBCollection<T, K> getReferenceCollection(JacksonCollectionKey collectionKey) { JacksonDBCollection<T, K> collection = referencedCollectionCache.get(collectionKey); if (collection == null) { collection = new JacksonDBCollection<T, K>(getDB().getCollection(collectionKey.getName()), collectionKey.getType(), collectionKey.getKeyType(), objectMapper, features); referencedCollectionCache.put(collectionKey, collection); } return collection; }
@SuppressWarnings({"unchecked"}) T[] convertFromDbObjects(DBObject... dbObjects) throws MongoException { T[] results = (T[]) new Object[dbObjects.length]; for (int i = 0; i < dbObjects.length; i++) { results[i] = convertFromDbObject(dbObjects[i]); } return results; }
/** * Returns the number of documents in the collection * that match the specified query * * @param query query to select documents to count * @param fields fields to return * @param limit limit the count to this value * @param skip number of entries to skip * @return number of documents that match query and fields * @throws MongoException If an error occurred */ public long getCount(T query, T fields, long limit, long skip) throws MongoException { return dbCollection.getCount(convertToBasicDbObject(query), convertToBasicDbObject(fields), limit, skip); }
/** * Get the saved IDs. This may be useful for finding out the IDs that were generated by MongoDB if no IDs were * supplied. * * @return The saved IDs */ public List<K> getSavedIds() { if (dbObjects.length > 0 && dbObjects[0] instanceof JacksonDBObject) { throw new UnsupportedOperationException("Generated _id retrieval not supported when using stream serialization"); } List<K> ids = new ArrayList<K>(); for (int i = 0; i < dbObjects.length; i++) { ids.add((K) jacksonDBCollection.convertFromDbId(dbObjects[i].get("_id"))); } return ids; }
DBObject createIdQuery(K object) { return new BasicDBObject("_id", convertToDbId(object)); }
/** * Get the objects that were saved. These will contain the updated IDs if the IDs were generated. * <p/> * This operation only works if object serialization is used. If stream serialization is used, the IDs are * generated by the database, and cannot be known. * <p/> * Note, this operation is a little expensive because it has to deserialise the objects. If you just want the IDs, * call getSavedIds() instead. * * @return The saved objects */ public T[] getSavedObjects() { // Lazily generate the object, in case it's not needed. if (objects == null) { if (dbObjects.length > 0) { if (dbObjects[0] instanceof JacksonDBObject) { throw new UnsupportedOperationException("Saved object retrieval not supported when using stream serialization"); } } objects = jacksonDBCollection.convertFromDbObjects(dbObjects); } return objects; }
@GET @Timed public List<Blog> blogsTimeline() { DBCursor<Blog> dbCursor = collection.find(); List<Blog> blogs = new ArrayList<>(); while (dbCursor.hasNext()) { Blog blog = dbCursor.next(); blogs.add(blog); } return blogs; }
/** * Finds a collection that is prefixed with this collection's name. * A typical use of this might be * <blockquote><pre> * DBCollection users = mongo.getCollection( "wiki" ).getCollection( "users" ); * </pre></blockquote> * Which is equivalent to * <pre><blockquote> * DBCollection users = mongo.getCollection( "wiki.users" ); * </pre></blockquote> * * @param n the name of the collection to find * @param type The type of the collection * @return the matching collection */ public <S, L> JacksonDBCollection<S, L> getCollection(String n, Class<S> type, Class<L> keyType) { return wrap(getDB().getCollection(getName() + "." + n), type, keyType, objectMapper); }
/** * Fetch a collection of dbrefs. This is more efficient than fetching one at a time. * * @param collection the collection to fetch * @param fields The fields to retrieve for each of the documents * @return The collection of referenced objcets */ public <R, RK> List<R> fetch(Collection<DBRef<R, RK>> collection, DBObject fields) { Map<JacksonCollectionKey, List<Object>> collectionsToIds = new HashMap<JacksonCollectionKey, List<Object>>(); for (DBRef<R, RK> ref : collection) { if (ref instanceof FetchableDBRef) { JacksonCollectionKey key = ((FetchableDBRef) ref).getCollectionKey(); List<Object> ids = collectionsToIds.get(key); if (ids == null) { ids = new ArrayList<Object>(); collectionsToIds.put(key, ids); } ids.add(getReferenceCollection(key).convertToDbId(ref.getId())); } } List<R> results = new ArrayList<R>(); for (Map.Entry<JacksonCollectionKey, List<Object>> entry : collectionsToIds.entrySet()) { for (R result : this.<R, RK>getReferenceCollection(entry.getKey()).find( new QueryBuilder().put("_id").in(entry.getValue()).get(), fields)) { results.add(result); } } return results; }
@Override public void run(Reader30Configuration configuration, Environment environment) throws Exception { Mongo mongo = new Mongo(configuration.mongohost, configuration.mongoport); DB db = mongo.getDB(configuration.mongodb); JacksonDBCollection<Blog, String> blogs = JacksonDBCollection.wrap(db.getCollection("blogs"), Blog.class, String.class); MongoManaged mongoManaged = new MongoManaged(mongo); environment.manage(mongoManaged); environment.addHealthCheck(new MongoHealthCheck(mongo)); environment.addResource(new BlogResource(blogs)); environment.addResource(new IndexResource(blogs)); }