Ask Your Question
4

How can I retrieve the $count together with other attributes using MongoDb Aggregation?

asked 2023-07-02 14:34:34 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-02 14:41:02 +0000

ladyg gravatar image

You can use the $group stage in MongoDB aggregation to retrieve the count along with other attributes.

Here's an example:

db.collection.aggregate([
  {$match: {someField: "someValue"}}, // filter documents
  {$group: {
    _id: "$someField", // group by someField
    count: {$sum: 1}, // count documents in group
    otherAttribute: {$first: "$otherField"} // retrieve first value of otherField in group
  }}
])

In this example, the aggregation pipeline first filters documents that have a specific value in the someField field. Then it groups the remaining documents by the someField field using the $group stage.

Within the group, it calculates the count of documents in the group using the $sum operator and assigns it to the field count. It also retrieves the first value of the otherField field in the group using the $first operator and assigns it to the field otherAttribute.

The resulting output will be a list of groups, each containing the someField, count, and otherAttribute fields.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-02 14:34:34 +0000

Seen: 9 times

Last updated: Jul 02 '23