简体   繁体   中英

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

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...> }
])

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

Grouping by null you ensure all values are grouped. And $push the $$ROOT object (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM