映射数组中的可选字段

时间:2017-08-10 07:11:27

标签: mongodb aggregation-framework

mongodb聚合查询有问题。

这是我正在使用的数据库架构

    {
 "_id":""
 "authors" : [ 
        {
            "name" : "aaa",
            "city" : "xyz",
            "book":{"name":"blah"}
        }, 
        {
            "name" : "bbb",
            "city" : "abc",
        }, 
        {
            "name" : "ccc",
            "city" : "xyz",
            "book":{"name":"blah blah"}
        }, ]
}

使用此查询 -

 db.book.aggregate( [ { $project: {"id":1, "authors.name":1, "authors.city":1,
           "authors.books":
        {
            $let :{
                vars:{"book":{$ifNull:["$authors.book", "absent"]}},
                in:  { 
                     $cond: {if: {$eq:["$$book","absent"]},
                             then:[],
                             else:["$author.book"]}
                     }
                 }
      }
      }
      },{ $out :"book" }])

导致以下输出 -

{
 "_id":""
 "authors" : [ 
        {
            "name" : "aaa",
            "city" : "xyz",
            "books":[[{"name":"blah"}],
                    [{"name":"blah blah"}]]
        }, 
        {
            "name" : "bbb",
            "city" : "abc",
            "books":[[{"name":"blah"}],
                    [{"name":"blah blah"}]]
        }, 
        {
            "name" : "ccc",
            "city" : "xyz",
            "books":[[{"name":"blah"}],
                    [{"name":"blah blah"}]]
        }, ]
}

这非常接近我需要/想要的东西 -

    {
 "_id":"",
 "authors" : [ 
        {
            "name" : "aaa",
            "city" : "xyz",
            "books":[
                     {"name":"blah"},
                     {"genre":"blah1"}]
        }, 
        {
            "name" : "bbb",
            "city" : "abc",
            "books":[]
        }, 
        {
            "name" : "ccc",
            "city" : "xyz",
            "books":[
                    {"name":"blah blah"},
            {"genre":"blah1"}]
        }
    ]
}

问题在于,一位作者的书的价值被分配给所有作者。如果只有一个作者,代码工作正常,但是当代码超过1时失败。 Haven没有尝试将这个值分配给流派, 使用MongoDB版本3.2.16,帮助我弄清楚我做错了什么以及如何纠正它。提前谢谢。

0 个答案:

没有答案