本文介绍了MongoDB过滤多个子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongo DB中有一个这样的文档结构,我想过滤以仅显示活动的子文档:活动的汽车和活动的水果.
I Have a document structured like this in mongo DB, and I want to filter to show only active subdocuments: active cars and active fruits.
{ "name":"Andre", "fruits":[ { "active":true, "fruitname":"apple" },{ "active":false, "fruitname":"banana" } ], "cars":[ { "active":false, "carname":"ford" },{ "active":true, "carname":"GM" }, ] }这是我想要的结果.
{ "name":"Andre", "fruits":[ { "active":true, "fruitname":"apple" } ], "cars":[ { "active":true, "carname":"GM" }, ] }我已经尝试过Aggregate,但是当任何汽车或水果活动时,它什么也不会返回.
I've tried Aggregate but when any cars or any fruits active, it's return nothing.
m_object.aggregate([ { $match : { "name": "andre" }}, { $unwind : "$fruits" }, { $unwind : "$cars" }, { $match : { 'fruits.active':{$eq: true} }}, { $match : { 'cars.active':{$eq: true} }}, { $group : { "name": "$name", cars: { $addToSet : "$cars" } fruits: { $addToSet : "$fruits" } }} ], function (err, result) { if (err) { console.log(err); return; } console.log('result'); });是否可以忽略那些子文档中的"active":false子文档?
Is there any way to omit the "active":false subdocuments in those subdocuments?
推荐答案使用以下聚合管道来获得所需的结果:
Use the following aggregation pipeline to get the desired result:
var pipeline = [ { "$match": { "name": "Andre", "fruits.active": true, "cars.active": true } }, { "$unwind": "$fruits" }, { "$unwind": "$cars" }, { "$match": { "fruits.active": true, "cars.active": true } }, { "$group": { "_id": { "_id": "$_id", "name": "$name" }, "cars": { "$addToSet" : "$cars" }, "fruits": { "$addToSet" : "$fruits" } } }, { "$project": { "_id": 0, "name": "$_id.name", "cars": 1, "fruits": 1 } } ] m_object.aggregate(pipeline) .exec(function (err, result) { if (err) { console.log(err); return; } console.log('result'); });或者您可以使用 聚合管道 生成器如下:
Or you can use the aggregation pipeline builder as follows:
m_object.aggregate() .match({ "name": "Andre", "fruits.active": true, "cars.active": true }) .unwind("fruits") .unwind("cars") .match({ "fruits.active": true, "cars.active": true }) .group({ "_id": { "_id": "$_id", "name": "$name" }, "cars": { "$addToSet" : "$cars" }, "fruits": { "$addToSet" : "$fruits" } }) .project({ "_id": 0, "name": "$_id.name", "cars": 1, "fruits": 1 }) .exec(callback);更多推荐
MongoDB过滤多个子文档
发布评论