我有问题陈述,其中我需要在“config.first.second”子级别的所有字段名称,其中include字段至少为真一次。 这是我的mongo集合对象。
[ {
"_id" : ObjectId("560e97f4a78eb445cd2d75e5"),
"config" : {
"first" : {
"second" : {
"field1" : {
"include":"true"
},
"field3" : {
"include":"true"
},
"field9" : {
"include":"false"
},
"field6" : {
"include":"false"
}
}
}
},
"date_created" : "Fri Oct 02 14:43:00 UTC 2015",
"last_updated" : "Mon Apr 11 15:26:37 UTC 2016",
"id" : ObjectId("560e97f4a78eb445cd2d75e5")
},
{
"_id" : ObjectId("56154465a78e41c04692af20"),
"config" : {
"first" : {
"second" : {
"field1" : {
"include":"true"
},
"field3" : {
"include":"false"
},
"field7" : {
"include":"true"
}
}
}
},
"date_created" : "Wed Oct 07 16:12:21 UTC 2015",
"last_updated" : "Mon Apr 11 15:18:58 UTC 2016",
"id" : ObjectId("56154465a78e41c04692af20")
}
]
使用上面的mongo集合。查询必须返回结果
["field1","field3","field7"]
答案 0 :(得分:2)
您可以使用mapReduce:
运行db.collection.mapReduce(
function() {
Object.keys(this.config.first.second)
.filter( k => this.config.first.second[k].include === "true" )
.forEach(k => emit(k,1) );
},
function() { },
{
"out": { "inline": 1 },
}
)['results'].map( d => d._id )
如果你有MongoDB 3.4,那么你可以使用.aggregate()
:
db.collection.aggregate([
{ "$project": {
"field": {
"$filter": {
"input": { "$objectToArray": "$config.first.second" },
"as": "f",
"cond": { "$eq": [ "$$f.v.include", "true" ] }
}
}
}},
{ "$unwind": "$field" },
{ "$group": { "_id": "$field.k" } }
]).toArray().map(d => d._id)
返回:
[
"field1",
"field3",
"field7"
]