可以使用通配符排除MongoDB中的嵌套字段吗?

时间:2018-01-09 15:48:46

标签: mongodb

假设我有一份文件:

{
   "_id": "123",
   "fruit": {
     "apple": {
       "species": "Malus pumila",
       "taste": "Not bad"
     },
     "orange": {
       "species": "Citrus sinensis",
       "taste": "Pretty good"
     }
   }
}

我想在db.food.find({}, {"fruit.*.taste": 0})的行中做一些事情,不在查询结果中包含品味字段:

{
   "_id": "123",
   "fruit": {
     "apple": {
       "species": "Malus pumila"
     },
     "orange": {
       "species": "Citrus sinensis"
     }
   }
}

通过传统查询或聚合管道可以实现这样的事情吗?

1 个答案:

答案 0 :(得分:1)

目前还没有办法在子文档上排除通配符。但是,您可以将汇总管道与$project个管道以及$objectToArray$arrayToObject运算符一起使用,以获得相同的结果:

db.test.aggregate([
    { $project: { "fruit" : { $objectToArray: "$fruit" } } },
    { $project: { "fruit.v.taste" : 0} },
    { $project: { "fruit" : { $arrayToObject: "$fruit"} } }
]);
{
        "_id" : "123",
        "fruit" : {
                "apple" : {
                        "species" : "Malus pumila"
                },
                "orange" : {
                        "species" : "Citrus sinensis"
                }
        }
}

第一个$ project { "fruit" : { $objectToArray: "$fruit" } }fruit文档转换为键/值数组:

{
        "_id" : "123",
        "fruit" : [
                {
                        "k" : "apple",
                        "v" : {
                                "species" : "Malus pumila",
                                "taste" : "Not bad"
                        }
                },
                {
                        "k" : "orange",
                        "v" : {
                                "species" : "Citrus sinensis",
                                "taste" : "Pretty good"
                        }
                }
        ]
}

一旦我们以数组格式获得它,我们就可以使用标准投影排除taste字段,不包括字段{ $project: { "fruit.v.taste" : 0} }

{
        "_id" : "123",
        "fruit" : [
                {
                        "k" : "apple",
                        "v" : {
                                "species" : "Malus pumila"
                        }
                },
                {
                        "k" : "orange",
                        "v" : {
                                "species" : "Citrus sinensis"
                        }
                }
        ]
}

然后我们可以使用$arrayToObject运算符构建备份文档。

更多信息可以在这里找到: $ arrayToObject - https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/ $ objectToArray - https://docs.mongodb.com/manual/reference/operator/aggregation/objectToArray/