我想检索所有具有其变体的文档,但变体具有isDeleted属性:true
const configs = mongoose.model('configs', new mongoose.Schema(defining it to use mixed schema here);
我想编写nosql查询以返回这样的文档,而没有varients数组的第二个元素,有什么帮助!
[
{
"_id": "5c1d023422ffef2282619192",
"title": "Iphone 6S",
"varients": [
{
"isDeleted": false,
"_id": "5c1d023422ffef2282619196",
"title": "Iphone 6S black 64GB"
},
{
"isDeleted": true,
"_id": "5c1d023422ffef2282619193",
"title": "Iphone 6S green 32GB"
}
]
}
]
答案 0 :(得分:0)
您可以将$addFields
聚合管道与$filter
配合使用,以通过variants
字段过滤isDeleted
聚合管道
db.t4.aggregate([
{$addFields : {
varients : {$filter : {
input :"$varients",
as : "v",
cond : {$not : "$$v.isDeleted"}
}}
}}
])
样品采集
> db.t4.findOne()
{
"_id" : "5c1d023422ffef2282619192",
"title" : "Iphone 6S",
"varients" : [
{
"isDeleted" : false,
"_id" : "5c1d023422ffef2282619196",
"title" : "Iphone 6S black 64GB"
},
{
"isDeleted" : true,
"_id" : "5c1d023422ffef2282619193",
"title" : "Iphone 6S green 32GB"
}
]
}
结果
> db.t4.aggregate({$addFields : {varients : {$filter : {input :"$varients", as : "v", cond : {$not : "$$v.isDeleted"}}}}}).pretty()
{
"_id" : "5c1d023422ffef2282619192",
"title" : "Iphone 6S",
"varients" : [
{
"isDeleted" : false,
"_id" : "5c1d023422ffef2282619196",
"title" : "Iphone 6S black 64GB"
}
]
}
>