Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

mongodb add counter to each retrieved document

Hey is there a way to add to each document retrieved from mongo a counter?

So lets say we have users : {_id, name} in mongo . I want to fetch them all and to each retrieved document I want to add a counter field and increase it as I fetch the docs.

so the result would be

users : [{_id: "some_id_1", name: "john", counter: 1}, {_id: "some_id_2", name: "bob", counter: 2]

so this counter field would be generated on the fly ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Although answer mentionned by @prasad_ seems to work, $unwind has since Mongodb 3.2 includeArrayIndex option that make it easier to achieve :

db.collection.aggregate([
  {
    $group: {
      _id: null,
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $unwind: {
      path: "$data",
      includeArrayIndex: "counter",

    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$data",
          {
            counter: {
              $add: [
                "$counter",
                1
              ]
            }
          }
        ]
      }
    }
  }
])

Last stage is here just to reshape your docs, and add 1 to each counter, as it is 0-based (based on array index)

You can test it here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...