Hello Mongo Community,
I have tried to search from multiple collection with $lookup and $facet and the aggregation query is as the follows where keyword is the search Term
let result = await db.collection(c1).aggregate(
[
{
$match:{
name: keyword
}
},
{
$group: {
_id: 0,
c1: {
$push: "$$ROOT"
}
}
},
{
"$facet": {
c2: [{
"$lookup": {
"from": '$c2',
"pipeline": [
{ "$match": { $text: {$search: keyword}} }
],
"as": c2
}
}],
c3: [{
"$lookup": {
"from": '$c3',
"pipeline": [
{ "$match": { $text: {$search: keyword}} }
],
"as": c3
}
}],
}},
{ "$project": {
"data": {
"$concatArrays":concatArray
}
}},
{
$unwind: "$data"
},
{
$replaceRoot:{newRoot: '$data'}
},
]).toArray()
This give the query as the follows
[
{
_id: 0,
c1: [ [Object] ],
c2: [ [Object] ]
},
{
_id: 0,
c1: [ [Object] ],
c3: [ [Object] ]
}
]
but what I want to do is to give a single object with collectiion as keys which is as follows
{
_id: 0,
c1: [ [Object] ],
c2: [ [Object] ],
c3: [ [Object] ]
}
so how can I improve my query?
I have tried to use $group at the last with this syntax
$group:{
_id:"$_id",
c1:{
$push:"$_c1"},
c2:{
$push:"$_c2"},
c3:{
$push:"$_c3"}
}
but this give result on double nested array like this and I have to unwind the every single field.
{
_id: 0,
c1: [ [ [Object] ] ],
c2: [ [ [Object] ] ],
c3: [ [ [Object] ] ]
}
with $first it give null ( I don’t know why and please let me know if it is okay)
so is there better accumulator or way to achieve the result I have intended. Thanks in advance