【发布时间】:2011-05-24 22:05:53
【问题描述】:
如何在文档中有嵌套文档的地方搜索 mongodb 文档。例如,我有一组私人消息。每条私人消息都有两个嵌套的文档——一个代表发送用户,另一个代表接收用户。两个嵌套文档的格式为 -
用户 ID:34343, 名称:乔博客
我希望能够搜索用户发送的所有邮件消息(例如搜索发件人用户嵌套文档)。
我正在使用 java 驱动程序。我需要创建一个代表嵌套文档的 DBObject 吗?
谢谢
【问题讨论】:
如何在文档中有嵌套文档的地方搜索 mongodb 文档。例如,我有一组私人消息。每条私人消息都有两个嵌套的文档——一个代表发送用户,另一个代表接收用户。两个嵌套文档的格式为 -
用户 ID:34343, 名称:乔博客
我希望能够搜索用户发送的所有邮件消息(例如搜索发件人用户嵌套文档)。
我正在使用 java 驱动程序。我需要创建一个代表嵌套文档的 DBObject 吗?
谢谢
【问题讨论】:
据我了解,您的文档结构如下:
{
"someProperty" : 1,
"sendingUser" : {
userID : 34343,
name : "Joe Bloggs"
},
"recivingUser" : {
userID : 34345,
name : "Joe Bloggs"
}
}
因此,如果您需要查找 userID = 34345 的发送用户,您只需要执行以下操作(我只是认为是这样,因为实际上我正在使用 mongo 的 c# 驱动程序):
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 driver的教程
【讨论】:
$eq :-(
query.put("sendingUser.userID", 34345);。
query.put("sendingUser.userID", 34345); 返回了null,我认为它不起作用,但记录不在数据库中,我的错误。它工作正常。
适用于 MongoDB Java 驱动程序 v3.2.2。你可以这样做:
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.userID\": \"34343\"}"));
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.name\": \"Joe Bloggs\"}"));
您可以将$eq 放在 JSON 样式的查询字符串中。喜欢{ <field>: { $eq: <value> } }。
【讨论】: