在MongoDb中,使用Projection,删除带有一个空对象[{}]的数组

时间:2017-09-06 09:52:07

标签: mongodb mongodb-query

在MongoDb中,使用Projection,我想删除一个包含一个空对象 [{}] 的数组,该数组来自$ unwind preserveNullAndEmptyArrays&组。

[{
  "title": "Papaye",
  "childrens": [{}],
  "parents": [{
      "title": "Arbres fruitiers",
      "url": "/documents/plantes/arboriculture/arbres-fruitiers"
    }
  ],
  "url": "/documents/plantes/arboriculture/arbres-fruitiers/papaye"
},
{
  "title": "Arbres fruitiers",
  "childrens": [{
      "title": "Tavelure",
      "url": "/documents/maladies/tavelure"
    },
    {
      "title": "Longane",
      "url": "/documents/plantes/arboriculture/arbres-fruitiers/longane"
    }],
  "parents": [{
      "title": "Arboriculture",
      "url": "/documents/plantes/arboriculture"
     }],
 "url": "/documents/plantes/arboriculture/arbres-fruitiers"
}

管道如:

var pipeline = [];
pipeline.push({$match:{url:/^\//}});
(...)
var proj = {};
proj.title = true;
proj.parents = true;
proj.url = true;

proj.parents = ???
proj.childrens = ???

pipeline.push({$project:proj});
db.getCollection('Pages').aggregate(pipeline)

提前致谢

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。只测试第一个数组条目的url是否为null。

proj.childrens = {
    "$cond", [
                "$eq", [
                        "$arrayElemAt",["$childrens.url",0],
                        null
                    ],
                [],
                "$childrens"
              ]
};