0

Shape of the document(s) in the collection

[
  {
    "predictions": [
      "611b85b9b2b924245526c125"
    ],
    "_id": "611e40b6dd381f18cf63d15f",
   
    "__v": 0
  },
  {
    "predictions": [
      "611b85b9b2b924245526c125"
    ],
    "_id": "611e40b6dd381f18cf63d160",
    
    "__v": 0
  }
]

My Aggregation pipeline

        ActiveFixture.aggregate([
                {$match:{fixture:{$in:fixtureIds}}},
                {$project:{"predictions":1, _id:0}},
                {$unwind:"$predictions"},
                {$group:{_id:'blah', "Predictions":{"$push":"$predictions"}}}
               
               
                
        ]).exec()

Current output:

[
  {
    "_id": "blah",
    "Predictions": [
      "611b85b9b2b924245526c125",
      "611b85b9b2b924245526c125",
      "611b85b9b2b924245526c125",
      "611b85b9b2b924245526c125"
    ]
  }
]

Desired output would be all values from predictions arrays as an single array:

["611b85b9b2b924245526c125", "611b85b9b2b924245526c125", "611b85b9b2b924245526c125"]

Any ideas, pointers would be much appreciated. Obviously I am well aware it's trivial to transform current output to desired shape with JS but goal is to achieve final product with MongoDB Aggregation

3 Answers 3

2

$unwind all predictions, group by null(all collection as 1 group), and $push all members to array.

Test code here

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$predictions"
    }
  },
  {
    "$group": {
      "_id": null,
      "predictions": {
        "$push": "$predictions"
      }
    }
  },
  {
    "$project": {
      "_id": 0
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! I have no idea what just happened but it's actually works
0

As you want to skip your id column so you should use the $skip command of mongodb. It allows you to skips number of documents or any other condition as applied by you

1 Comment

{$skip:"$_id"} gives error: MongoError: Argument to $skip must be a number not a string
0

If you want to conditionally remove some data from your output. You can use the following query

db.collection.aggregate( [ { $project : { "_id" : 0, "predictions" : 1 } } ] )

1 Comment

I have already tried that but result is ``` [ { "Predictions": [ "611b85b9b2b924245526c125", "611b85b9b2b924245526c125", "611b85b9b2b924245526c125", "611b85b9b2b924245526c125" ] } ] ``` Still nested array with unnecessary keys instead of top level array with string items. I guess this is best I can get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.