更新MongoDB中的第二级数组元素

时间:2015-05-26 16:32:05

标签: arrays mongodb nested updates

如何在以下mongo集合中将学生1的活动字段更新为 true 。 (鉴于此,我们知道hostel_name,room_no,student_id要更新)

{
  "hostel_name": "ABC",
  "rooms": [
    {
      "room_no": 1,
      "students": [
        {
          "student_id": 1,
          "active": false
        },
        {
          "student_id": 2,
          "active": true
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:-1)

解答:

db.collectionname.update({"rooms.students.student_id" : 1},{"$set" : {"rooms.$.students.0.active" : true}})

{
    "_id" : ObjectId("5564fb68c8fc4ec0f15c6dd4"),
    "hostel_name" : "ABC",
    "rooms" : [ 
        {
            "room_no" : 1,
            "students" : [ 
                {
                    "student_id" : 1,
                    "active" : true
                }, 
                {
                    "student_id" : 2,
                    "active" : true
                }
            ]
        }
    ]
}
相关问题