从嵌套数组文档中检索特定项目

时间:2018-12-21 15:48:23

标签: node.js mongodb express nosql

我想检索所有具有其变体的文档,但变体具有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"
      }
    ]
  }
]

1 个答案:

答案 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"
                }
        ]
}
>