node.js - Mongoose中的多个嵌套过滤器
问题描述
我的 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 和内部检查 dat 进行过滤 我必须仅列出状态为“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
]
}
]
}
因此,我必须根据 comments.insId 过滤对象,并且必须从该单个对象中删除基于 status 的位置内的对象。我如何在猫鼬中得到这个结果
解决方案
$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"]}}}
}
}
}
}
}
推荐阅读
- html - 字体真棒图标没有出现
- java - 设置列标题的最大高度 - NatTable
- ssl - 我正在尝试使用 PoolingHttpClientConnectionManager 和 ClosableHttpClient 为 HTTPS 创建具有单个连接的连接池并重用它
- razor - SelectListItem 显示类的名称而不是文本字段
- javascript - 模拟点击角度元素
- mongodb - 使用 TypeOrm 连接到 MongoDB Atlas?
- docker - 群清理容器/图像还是我应该运行系统修剪?
- python - 从 argv 获取 IP 失败
- python - 识别和更改组内的极端日期时间异常值
- reactjs - React 和 momentjs - 检查两个日期数组并返回布尔值