开发者

mongodb: inc high level document and embedded document

I want to increment two values, one in high level document and one in emb开发者_运维知识库edded document:

{
  studentId: "x1"
  numberOfAttending: 2

  courses: [
    {
      courseId:"y1"
      numberOfAttending: 1
    },
    {
      courseId:"y2"
      numberOfAttending: 1
    }
  ]
}

How could i inc the number of attending for student and for the course (upsert). and could i do it with a single update query ?


That's going to be tough since courses is an array. You'll need to know the index of the course you want to update, then do something like:

{ '$inc' : {numberOfAttending : 1, 'courses.1.numberOfAttending' : 1}}

Have you thought about switching it to a single embedded doc with courseId as a key for each course? If so, you can run a command like this to increment both. This doesn't depend on position so it's going to be less fragile:

{ '$inc' : { numberOfAttending : 1, 'courses.y2.numberOfAttending' : 1}}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜