MongoDB嵌套文档搜索 [英] MongoDB nested documents searching
问题描述
如何搜索文档中嵌套文档的mongodb文档。例如,我有一组私人消息。每条私人消息都有两个嵌套文档 - 一个代表发送用户,另一个代表接收用户。两个嵌套文档都有以下形式 -
How do I search through mongodb documents where documents have nested documents. For example I have a collection of private messages. Each private message has two nested documents - one representing the sending user and the other representing the receiving use. Both nested documents have the form -
userID:34343,
名称:Joe Bloggs
userID: 34343, name: Joe Bloggs
I希望能够搜索用户发送的所有邮件消息(例如,搜索发件人用户嵌套文档)。
I would like to be able to search for all mail messages sent by a user (e.g. search the sender user nested document).
我正在使用java驱动程序。我是否需要创建一个代表嵌套文档的DBObject?
I am using the java driver. Do I need to create a DBObject which represents the nested document?
谢谢
推荐答案
据我所知你有这样的文件结构:
As i understand u have document structure like this:
{
"someProperty" : 1,
"sendingUser" : {
userID : 34343,
name : "Joe Bloggs"
},
"recivingUser" : {
userID : 34345,
name : "Joe Bloggs"
}
}
所以如果你需要找到发送用户ID = 34345的用户你只需要做以下(我只是认为是这样,因为实际上我正在使用c#driver for mongo):
So if you need find sending user with userID = 34345 you just need do following(i just think that is so, because actually i am working with 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 driver
这篇关于MongoDB嵌套文档搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!