MongoDB嵌套文档搜索
如何搜索文档具有嵌套文档的mongodb文档。 例如,我有一组私人消息。 每条私人消息都有两个嵌套文档 – 一个代表发送用户,另一个代表接收用户。 两个嵌套文档都有以下forms –
userID:34343,名称:Joe Bloggs
我希望能够搜索用户发送的所有邮件消息(例如,搜索发件人用户嵌套文档)。
我正在使用java驱动程序。 我是否需要创建一个代表嵌套文档的DBObject?
谢谢
据我所知你有这样的文档结构:
{ "someProperty" : 1, "sendingUser" : { userID : 34343, name : "Joe Bloggs" }, "recivingUser" : { userID : 34345, name : "Joe Bloggs" } }
因此,如果您需要找到发送用户ID = 34345的用户,您只需要执行以下操作(我只是认为是这样,因为实际上我正在使用c#driver for mongo):
DBCollection coll = db.getCollection("privateMessages") query = new BasicDBObject(); query.put("sendingUser.userID", new BasicDBObject("$eq", 34345)); cur = coll.find(query); // all documents with sendingUser.userID = 34345 will be //returned by cursor
另请查看java驱动程序的教程
对于MongoDB Java驱动程序v3.2.2。 你可以这样做:
FindIterable iterable = collection.find(Document.parse("{\"sendingUser.userID\": \"34343\"}")); FindIterable iterable = collection.find(Document.parse("{\"sendingUser.name\": \"Joe Bloggs\"}"));
您可以将$eq
放在JSON样式查询字符串中。 与{
类似。