如何从聚合mongoDB获得结果?
我的收藏如下:如何从聚合mongoDB获得结果?,mongodb,mongoose,mongodb-query,aggregation-framework,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我的收藏如下: { "_id" : ObjectId("5716617f4af77ca97a9614bd"), "flag": { "status": true, "userId": ObjectId"606b0e9f00bece43471baa50")}, "text" : "Main Comment 1", "reply&
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "flag": { "status": true, "userId": ObjectId"606b0e9f00bece43471baa50")}, "text" : "Main Comment 1", "reply" : [ { "_id" : ObjectId("571661cd4af77ca97a9614c1"), "flag": { "status": true }, "text" : "Main Comment 1 reply 1" }, { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "flag": { "status": true, "userId": ObjectId("606b0e9f00bece43471baa48")}, "text" : "Main Comment 1 reply 2" } ] }
预期结果是,
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { } }
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "text" : "Main Comment 1 reply 1" } }
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "text" : "Main Comment 1 reply 2" } }
这是我正在使用的查询:
db.comments.aggregate([
{ $unwind: { path: "$reply", preserveNullAndEmptyArrays: true } },
{ $match: { $or: [ { 'flag.status': true }, { 'reply.flag.status': true }]} },
])
通过使用此代码,我没有得到预期的结果。
请告诉我该怎么办?
将比赛阶段放在第一位$match
解构$unwind
数组回复
显示必填字段并检查$project
回复的条件,如果
匹配,则返回标志
否则为空对象回复
如果注释集合
标记,则不按照我的要求工作。状态将为true
和reply.flag。此时状态将为false
,获得重复值。我已经更新了问题,以便您可以更好地查看。实际上,您已经添加了条件,其中一个条件在$match中应该为true,您可以解释您的$match条件或要求吗。我有注释集合,其中回复与数组一起存档。如果userA对此发表评论&userB回复。然后,UserC标记userA的注释。此时,userA的数据应该只显示这种操作在mongodb中是无效的事务,我建议您根据字段和条件的要求重新设计您的模式结构。
db.comments.aggregate([
{
$match: {
$or: [
{ "flag.status": true },
{ "reply.flag.status": true }
]
}
},
{
$unwind: {
path: "$reply",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
_id: 1,
text: 1,
reply: {
$cond: [
{ $eq: ["$reply.flag.status", true] },
{
_id: "$reply._id",
text: "$reply.text"
},
{}
]
}
}
}
])