migs
migs

Reputation: 174

Combining $facet results and formatting output

I have some data that I needed to sift through. I ended up using $facet to find the data, perform some calculations, and then combine the results using $concatArrays. My query looks something like this:

db.myColl.aggregate([
   {...},
   {...},
  {$facet:{res1:[...],res2:[...],...}},
  {$project:{"result": {$concatArrays:[res1, res2, res3, ...]}}}
  ])

and I get the output below:

{"results":[{"_id":0,"data":"1"},{"_id":1,"data":"2"},{"_id":2,"data":"3"}]}

However, I want to then iterate over the results of the query in python and would prefer the data to look like below

{"_id":0,"data":"1"}
{"_id":1,"data":"2"}
{"_id":2,"data":"3"}

This more closely resembles the output of a $match query. To my understanding $match returns a collection of documents rather than an array of elements.

How can I coax my pipeline to get the output to look like this? Ideally the change in my pipeline would be modifying the final $project stage or adding additional stages to my pipeline.

What I've tried so far

I've tried adding {$replaceRoot:{newRoot:"$results"} to the pipeline but I get an error because it does not accept arrays.

I've also tried adding {$project: {_id:"$results._id",data:"$results.data"} but this gives me

{
  "_id":[0,1,2],
  "data":[1,2,3]
}

Upvotes: 1

Views: 1799

Answers (2)

Selva
Selva

Reputation: 1

For me inside the concat array res1,res2,res3,.... was accessible only after adding $ in front of the variable name like "$res1".

db.myColl.aggregate([
   {...}
 {...},
  {$facet:{res1:[...],res2:[...],...}},
  {$project:{"result": {$concatArrays:["$res1", "$res2", "$res3", ...]}}},
{$unwind:{path:"$result"}},
  {$replaceRoot:{newRoot:"$results"}
  ])

Upvotes: 0

MD. Sani Mia
MD. Sani Mia

Reputation: 282

You can try to unwind operator after project then you use replaceRoot.

    db.myColl.aggregate([
   {...},
   {...},
  {$facet:{res1:[...],res2:[...],...}},
  {$project:{"result": {$concatArrays:[res1, res2, res3, ...]}}},
  {$unwind:{path:"$result"}},
  {$replaceRoot:{newRoot:"$results"}
  ])

Upvotes: 3

Related Questions