Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...