MongoDB在Java当中的稍复杂用法(内嵌Document或者Array的CRUD)

主要介绍三个内容,Document最外层的CRUD,内嵌Array数组的CRUD,内嵌Document的CRUD
参考网址: https://docs.mongodb.org/getting-started/java/
                     https://docs.mongodb.org/manual/reference/operator/projection/positional/


示例Document
exam
{
   "_id" : ObjectId("54c955492b7c8eb21818bd09"),
   "addresses" : {
      "address1",
      "address2"

   },
   "borough" : "Manhattan",
   "grades" : [
      {
         "date" : ISODate("2014-10-01T00:00:00Z"),
         "grade" : "A",
         "score" : 11
      },
      {
         "date" : ISODate("2014-01-16T00:00:00Z"),
         "grade" : "B",
         "score" : 17
      }
   ]

}




一.最外层基本CRUD

MongoCollection <Document> menuCollection = MongoUtils.getDB().getCollection( "exam");

1.insert
    public void insertOne(Exam e) {
        if (e.getId () == null) {
            e. setId( new ObjectId());
        }
        menuCollection.insertOne (MongoReflection .convertToDocument(menu));//自己定义的映射工具类
    }
2.find 
    public Menu findById(ObjectId eId ) {
        Document doc = menuCollection. find( eq( "_id", eId))
                .projection (exclude(" "grades" ))
                .first ();
        return MongoReflection.convertFromDocument (doc , Exam.class );
    }

3. delete
  
    public boolean deleteOne(ObjectId  eId ) {
        Document filter = new Document( "_id", eId);
        return menuCollection.deleteOne (filter ).wasAcknowledged ();
    }

4.update
    public boolean updateById(Exam  e) {
        if (e .getId () == null) {
            return false;
        }
        Document doc = MongoReflection.convertWithoutNull (menu );
        return menuCollection. updateOne( new Document( "_id", e.getId()),
                new Document( "$set", doc)).wasAcknowledged();
    }

5.find List
  
    public List <Restaurant > findByGroup(ObjectId groupId ) {
        FindIterable <Document > doc = restCollection
                .find (eq("groupId", groupId )).projection (
                        exclude( "thumb", "comment"));
        final List <Exam> list = new ArrayList<Exam >();
        if (doc == null) {
            return list;
        }
        doc. forEach( new Block< Document>() {
            @Override
            public void apply( final Document document) {
                Exam r = MongoReflection.convertFromDocument (document ,
                        Exam. class);
                list. add( r);
            }
        });
        return list;
    }

二.内嵌数组Array的CRUD操作
内嵌Array的操作
参考网址:https://docs.mongodb.org/manual/reference/operator/update/positional/#up._S_

1.insert
Java语法:
    public boolean insertOneThumb(ObjectId restId , String memberId) {
        return restCollection. updateOne( eq( "_id", restId),
                new Document( "$addToSet", new Document( "thumb", memberId)))
                .wasAcknowledged ();
    }
MongoDB 语法:db.exam.update({"_id":ObjectId("54c955492b7c8eb21818bd09")},{"$addToSet":{"addresses":"address3"}})
    Java语法:

2.单个更新update操作
MongoDB 语法:db.exam.update({"_id":ObjectId("54c955492b7c8eb21818bd09"),"addresses":"address1"},{"$set":{"addresses":"addressChange"}})
Java语法:
    restCollection. updateOne( and( eq( "_id",new ObjectId("54c955492b7c8eb21818bd09" )),eq("addresses", "address1")), new Document("addresses" ,"addressChange" ));

3.删除操作delete
 MongoDB语法:db.exam.update({"_id":ObjectId("54c955492b7c8eb21818bd09")},{"$pull":{"addresses":"address1"}})
 Java语法:
    restCollection. updateOne(  eq( "_id",new ObjectId("54c955492b7c8eb21818bd09" )),new Document("$pull", new Document("addresses" ,"address1" )));

4.查找操作
 MongoDB语法:db.exam.find({"addresses":{"$all":["address1"]}})
 Java语法:restCollection.find (all("addresses", Arrays.asList("address1")))
                .projection (exclude("grades")).first ();
参考网址:https://docs.mongodb.org/manual/reference/operator/query/all/#op._S_all


三.内嵌Document的CRUD操作
参考网址:  https://docs.mongodb.org/manual/reference/operator/update/push/#up._S_push
1.inset one document
  Java 代码:
 menuCollection.updateOne (eq("_id), new ObjectId("54c955492b7c8eb21818bd09")),
                new Document( "$push", new Document("grades" , document)))
                .wasAcknowledged ()
 MongoDB代码:db.menu.find({"_id":ObjectId("54c955492b7c8eb21818bd09")},{"$push":{里面是document的内容}})

2.delete one document form Array
 Java代码:
 menuCollection.updateOne(
                new Document ("_id","54c955492b7c8eb21818bd09"),
                new Document( "$pull", new Document("grades" ,
                        new Document( "grade", "A"))))
                .wasAcknowledged ();
  mongoDB代码:db.menu.update({"_id":ObjectId("54c955492b7c8eb21818bd09") },{"$pull":{"grades":{"grade":"A"}}})

3.update Document from array
    Java代码:
   
   menuCollection.updateOne (
                new Document( "grades.grade", "A"),
                new Document( "$set", new Document("grades.$.score" , 18) );
 

  mongoDB代码:db.menu.update({"grades.grade":"A"},{"$set":{"grades.$.score":18}})

4.select Document from array
  Java代码:
menuCollection
                .find (eq("grades.grade", "A"))
                .projection (new Document( "grades.$", 1)).first ()

 MongoDB代码;db.menu.find({"grades.grade":"A"},{"grades.$":1})  //只显示                                    
                                                                                                                                                                   
5.select list
  Java 代码:
           menuCollection.find(eq("_id" , new objectId(<span style="font-size:14px;"><span style="white-space: normal;">"54c955492b7c8eb21818bd09"</span></span>))
                .projection (new Document( "grades", 1)).first ()
  MongoDB代码:db.menu.find({"_id":ObjectId("54c955492b7c8eb21818bd09")},{"grades":1})



你可能感兴趣的:(mongodb,内嵌Document,内嵌Array数组)