Having a problem with mongodb aggregate query.
This is the db schema which I am using
{
"_id":""
"authors" : [
{
"name" : "aaa",
"city" : "xyz",
"book":{"name":"blah"}
},
{
"name" : "bbb",
"city" : "abc",
},
{
"name" : "ccc",
"city" : "xyz",
"book":{"name":"blah blah"}
}, ]
}
Using this query-
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" }])
Which results in the following output-
{
"_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"}]]
}, ]
}
This is very close to what I need/want-
{
"_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"}]
}
]
}
THe problem is that the value of book of one author gets assigned to all the authors. In case there is only one author the code works fine but fails when there are more than 1. Haven't tried assigning the value to genre yet, Using MongoDB version 3.2.16, help me in figuring out what am I doing wrong and how can I correct it. Thanks in advance.