我的json将是这样的:
{
"proj_id" : objectId1
"author": {},
"message": "This is post1",
"comments": [
{
"insId" : objectId1
"message": "Hii",
"location": [
{"select":"Y",id:1},
{"select":"N",,id:2}
]
},
{
"insId" : objectId2
"message": "Hii2",
"location": [
{"select":"Y",id:1},
{"select":"N",,id:2}
]
},
]
},
{
"proj_id" : objectId2
"author": {},
"message": "This is post2",
"comments": [
{
"insId" : objectId1
"message": "welcome2",
location: [
{"select":"Y",id:1},
{"select":"N",,id:2}
]
},
{
"insId" : objectId2
"message": "welcome4",
"location": [
{"select":"Y",id:1},
{"select":"N",,id:2}
]
}
]
}
预期输出:
{
"proj_id" : objectId1
"author": {},
"message": "This is post1",
"comments": [
{
"insId" : objectId1
"message": "Hii",
"location": [
{"select":"Y",id:1},
]
}
]
}
必须根据检查ID和内部检查数据进行过滤,我只需要列出状态为“ Y”的位置
我通过检查ID过滤尝试了以下代码
mongo.inspection.aggregate([
{$match: {"comments.insId": ObjectId(req.body.insId),"projectID":ObjectId(req.body.proj_id) }},
{$addFields : {"comments":{$filter:{ // We override the existing field!
input: "$comments",
as: "comments",
cond: {$eq: ["$$comments.insId", ObjectId(req.body.insId)]}
}}}}
],function(err,response){
console.log(response);
}
输出:
{
"proj_id" : objectId1
"author": {},
"message": "This is post1",
"comments": [
{
"insId" : objectId1
"message": "Hii",
"location": [
{"select":"Y",id:1},
{"select":"N",id:1}, // But it should not be list
]
}
]
}
因此,我必须根据comment.insId过滤对象,并根据该状态从该单个对象中删除该位置内的对象。如何获得猫鼬的结果
答案 0 :(得分:2)
将$map
与$filter
一起使用。
类似
{
"$addFields":{
"comments":{
"$map":{
"input":{
"$filter":{
"input":"$comments","as":"commentsf","cond":{"$eq":["$$commentsf.insId", ObjectId(req.body.insId)]}
}
},
"as":"commentsm",
"in":{
"insId":"$$commentsm.insId",
"message":"$$commentsm.message",
"location":{"$filter":{"input":"$$commentsm.location","as":"location","cond":{"$eq":["$$location.select","Y"]}}}
}
}
}
}
}
答案 1 :(得分:0)
尝试以下查询。在这里,我将滤除对象后放开对象。 然后再次过滤对象并将它们分组以得到原始格式。
mongo.inspection.aggregate([
{$match: {"proj_id": "objectId1", "comments.insId": " objectId1", "comments.location.select": "Y"}},
{$unwind:{path: "$comments", preserveNullAndEmptyArrays: false}},
{$match: {"comments.insId": " objectId1", "comments.location.select": "Y"}},
{$unwind:{path: "$comments.location", preserveNullAndEmptyArrays: false}},
{$match: {"comments.location.select": "Y"}},
{$group: {
_id: {proj_id : "$proj_id", ins_id: "$comments.insId"},
author : {$first: "$author"},
message : {$first: "$message"},
comm_message:{$first: "$comments.message"},
location:{$push: "$comments.location"}
}},
{$group: {
_id: "$_id.proj_id",
author : {$first: "$author"},
message : {$first: "$message"},
comments:{$push:{message: "$comm_message", location: "$location", insId: "$_id.ins_id"}}
}}
])
如果注释和位置数组中有很多条目,请使用这种方式。否则,请使用一些聚合数组运算符,例如过滤器和映射。