过滤字段而不输入空值

时间:2014-04-01 04:51:22

标签: mongodb aggregation-framework

系列:

{
"_id" : ObjectId("5338ec2a5b5b71242a1c911c"),
"people" : [ 
    {
        "name" : "Jhon"
    }, 
    {
        "age" : "30"
    }, 
    {
        "weight" : "80"
    }
]}

查询:db.tmp.aggregate({$ project:{" people.name":1}})

在问题中:

{
"result" : [ 
    {
        "_id" : ObjectId("5338ec2a5b5b71242a1c911c"),
        "people" : [ 
            {
                "name" : "Jhon"
            }, 
            {}, 
            {}
        ]
    }
],
"ok" : 1}

如何仅显示"名称"没有{}的字段空白?

1 个答案:

答案 0 :(得分:0)

在处理$unwind

中的数组时,您应该使用.aggregate()
 db.tmp.aggregate([
    { "$unwind": "$people" },
    { "$match": { "people.name": { "$exists": true } }},
    { "$project":{ "people.name":1 }}
 ])

如果你想把它作为一个数组然后分组回来:

 db.tmp.aggregate([
    { "$unwind": "$people" },
    { "$match": { "people.name": { "$exists": true } }},
    { "$group": { 
        "_id": "$_id", 
        "people": { "$push": { "name": "$people.name" } } 
    }}
 ])