mongoDB 不同 & 在同一查询中的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7419986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mongoDB distinct & where in same query?
提问by Inoryy
Let's say I have the following documents
假设我有以下文件
Article { Comment: embedMany }
Comment { Reply: embedMany }
Reply { email: string, ip: string }
I want to make a query that selects distinct Reply.ip
where Reply.email = xxx
我想进行一个选择不同Reply.ip
位置的查询Reply.email = xxx
Something like this, only it doesn't work..
像这样的东西,只是它不起作用..
db.Article.find("Comment.Reply.email" : "xxx").distinct("Comment.Reply.ip")
JSON export:
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"
}
]
}
]
}
I run: db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})
我跑:db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})
I expect: ["128.168.1.1", "192.168.1.1"]
我期望:["128.168.1.1", "192.168.1.1"]
I get: ["127.0.0.1", "128.168.1.1", "192.168.1.1", "192.168.2.1"]
我得到:["127.0.0.1", "128.168.1.1", "192.168.1.1", "192.168.2.1"]
回答by RameshVel
Distinct
query in mongo with condition works like this
Distinct
在 mongo 中查询条件是这样的
db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})
not other way around
不是其他方式
EDIT:
编辑:
I understand the problem now, inorder to match/filter subdocuments we need to use $elemMatch operator, like this
我现在明白这个问题了,为了匹配/过滤子文档,我们需要使用 $elemMatch 操作符,就像这样
db.Article.distinct("Comment.Reply.ip",{Comment: {$elemMatch: {"Reply.email" : "xxx"}}})
but this will not work if the sub-document contains sub arrays (in your case, you have array of replies). There is an existing issue $elemMatch on subArrayis opened. And its planned for mongo 2.1. You can check out the link for more info
但是如果子文档包含子数组(在您的情况下,您有回复数组),这将不起作用。有一个现有的问题$elemMatch on subArray被打开。它计划用于 mongo 2.1。您可以查看链接以获取更多信息
回答by Kaim
Maybe you could try this
也许你可以试试这个
db.Article.aggregate([
{$unwind: "$Comment"},
{$unwind: "$Comment.Reply"},
{$match: {"Comment.Reply.email": "xxx"}},
{$group: {_id: "$Comment.Reply.ip"}}
])
The result of example should be
示例的结果应该是
/* 1 */
{
"_id" : "192.168.1.1"
}
/* 2 */
{
"_id" : "128.168.1.1"
}
回答by Abilash Raghu
distinctdates=db.dailyreport_detailed.find(
{'uid':personemail,'month':searchdate2,'year':searchdate1}
)
.distinct('date_only')
where find will retrieve as per condition and distinct at the end will give unique dates.
其中 find 将根据条件检索,最后不同将给出唯一的日期。