首页 > 解决方案 > 猫鼬查询或聚合以删除某些子文档字段

问题描述

说我有以下文件

物品

{
    details: [
            {
                "title": "Name",
                "content": "",
                "is_private": false,
                "order": 0,
                "type": "text"
            },
            {
                "title": "Price",
                "content": "",
                "is_private": true,
                "order": 1,
                "type": "text"
            },
            {
                "title": "Company",
                "content": "",
                "is_private": false,
                "order": 2,
                "type": "text"
            }
        ],
}

如果我只想返回具有的子文档字段details,有is_private === false没有办法在猫鼬的查询中做到这一点,或者我是否需要使用聚合?

例如

ItemModel
    .find()
    // something should go here to remove

标签: mongodbmongoose

解决方案


如果您想使用本机聚合查询来执行此操作:

db.getCollection('item').aggregate([
   {
      $unwind:"$details"
   },
   {
      $match:{
         "details.is_private":true
      }
   },
   {
      $group:{
         _id:"$_id",
         details:{
            $push:"$details"
         }
      }
   }
])

输出:

{
    "_id" : ObjectId("5b7d0edb6cfaf771ecf675f0"),
    "details" : [ 
        {
            "title" : "Price",
            "content" : "",
            "is_private" : true,
            "order" : 1.0,
            "type" : "text"
        }
    ]
}

推荐阅读