MongoDB过滤多个子文档

编程入门 行业动态 更新时间:2024-10-23 18:32:53
本文介绍了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过滤多个子文档

本文发布于:2023-11-22 18:32:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!