How can we we give query for embedded documents through java driver?

拥有回忆 提交于 2020-01-04 05:15:31

问题


i want to access the embedded document through java query from mongodb.from a simple document its easy but how can we access from embedded document ?


回答1:


If I understand you correctly, you can find the answer of your question below.

Say you have the following nested document.

{ "key1" : "value1",
  "key2" : {
             "key21" : "value21",
             "key22" : "value22"
           }
}

If you mean to make query on the nested documents then you can access the embedded object using the following java code.

DBCollection coll = db.getCollection("collectionName");
BasicDBObject query = new BasicDBObject();
query.put("key2.key21", new BasicDBObject("$eq", "value21"));
DBCursor cur = coll.find(query);

If you mean to extract embedded document from the document then you can use Map/Reduce or Aggregation framework.

Ian Daniel is still added the code to insert nested documents that you asked. You can also visit this page to see some detailed examples.




回答2:


The following Java code will insert a document of the form {ID:23 {Name:{"FirstName": "Ahmad", "SecondName":"Khan"}}

Mongo mongo = new Mongo();
DB db = mongo.getDB("test");
DBCollection people = db.getCollection("people");

BasicDBObject name = new BasicDBObject();
name.put("FirstName", "Ahmad");
name.put("LastName", "Khan");

BasicDBObject person = new BasicDBObject();
person.put("ID", 23);
person.put("Name", name);

people.insert(person);


来源:https://stackoverflow.com/questions/11489728/how-can-we-we-give-query-for-embedded-documents-through-java-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!