获取具有匹配计数条件的嵌套对象的文档 [英] Get documents with nested objects matching count condition
本文介绍了获取具有匹配计数条件的嵌套对象的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是mongo noob,正在与mongo集合一起工作,记录如下:
I am a mongo noob and am working with a mongo collection with records that look like so:
{
"cats" [
{
"name": "fluffy",
"color": "red",
},
{
"name": "snowball",
"color": "white",
},
]
{
我想执行一个查询,以获取具有超过1只白猫的所有记录. MapReduce看起来很有前途,但似乎有些矫kill过正.感谢您的帮助.
I would like to perform a query that gets all records that have more than 1 white cats. MapReduce looks promising, but seems like overkill. Any help is appreciated.
推荐答案
You can use the aggregation framework to do this. You don't need to use the $where
operator.
db.collection.aggregate([
{ "$match": { "cats.color": "white" }},
{ "$project": {
"nwhite": { "$map": {
"input": "$cats",
"as": "c",
"in": { "$cond": [
{ "$eq": [ "$$c.color", "white" ] },
1,
0
]}
}},
"cats": 1
}},
{ "$unwind": "$nwhite" },
{ "$group": {
"_id": "$_id",
"cats": { "$first": "$cats" },
"nwhite": { "$sum": "$nwhite" }
}},
{ "$match": { "nwhite": { "$gte" :2 } } }
])
这篇关于获取具有匹配计数条件的嵌套对象的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文