Home > other >  How to aggregate documents flow into a single document with an array field? (mongodb)
How to aggregate documents flow into a single document with an array field? (mongodb)

Time:04-08

I have this dataSet:

[
  { 
    userId: 1,
    nickname: 'a'
  },
  { 
    userId: 2,
    nickname: 'b'
  },
  { 
    userId: 3,
    nickname: 'c'
  },
  ...
]

And I would like, using aggregate, to achieve this form:

{
  newField: 123456,
  users: [
    { 
      userId: 1,
      nickname: 'a'
    },
    { 
      userId: 2,
      nickname: 'b'
    },
    { 
      userId: 3,
      nickname: 'c'
    },
    ...
  ],
}

Where the flow of documents are combined together into a single array field inside of a single document, to which I'd like to add some extra fields. The initial dataSet is retrieved after some n'th stage in an aggregate pipeline.

Given all that:
What should the next stage be?
Do I need $group here?
How should my next stage look like?

db.users.aggregate([
  ...,
  { $whatStage: <what do I do inside of it...> }
])

CodePudding user response:

If I've understood correctly you can try this query:

Grouping by null you ensure all values are grouped. And $push the $$ROOT object (i.e. the document).

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "users": {
        "$push": "$$ROOT"
      }
    }
  }
])

Example here

Also, to add a new field you can either use $first into group (example) or a new stage with $set, $addFields or $project like this example

  • Related