假设我有以下文件
Article { Comment: embedMany }
Comment { Reply: embedMany }
Reply { email: string, ip: string }
我想进行一个查询,选择不同的 Reply.ip
其中 Reply.email = xxx
类似的东西,只是它不起作用..
db.Article.find("Comment.Reply.email" : "xxx").distinct("Comment.Reply.ip")
JSON 导出:
{
"_id":{
"$oid":"4e71be36c6eed629c61cea2c"
},
"name":"test",
"Comment":[
{
"name":"comment test",
"Reply":[
{
"ip":"192.168.2.1",
"email":"yyy"
},
{
"ip":"127.0.0.1",
"email":"zzz"
}
]
},
{
"name":"comment 2 test",
"Reply":[
{
"ip":"128.168.1.1",
"email":"xxx"
},
{
"ip":"192.168.1.1",
"email":"xxx"
}
]
}
]
}
我跑 : db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email": "xxx"})
我希望:["128.168.1.1", "192.168.1.1"]
我明白了:["127.0.0.1", "128.168.1.1", "192.168.1.1", "192.168.2.1"]
最佳答案
Distinct
在 mongo 中使用条件的查询是这样的
db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})
别无他法
编辑:
我现在明白了这个问题,为了匹配/过滤子文档,我们需要使用 $elemMatch 运算符,像这样
db.Article.distinct("Comment.Reply.ip",{Comment: {$elemMatch: {"Reply.email" : "xxx"}}})
但是如果子文档包含子数组(在您的情况下,您有回复数组),这将不起作用。存在一个问题 $elemMatch on subArray被打开。它计划用于 mongo 2.1。您可以查看链接了解更多信息
关于mongoDB 不同,在同一个查询中在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7419986/