更新嵌套字段中的值?

Update a value in a nested field?

user :["id": 1, userObj:[{"bookid": 1, "library":"Oxford", "taken":true}, {"bookid": 2, "library":"Cambridge", "taken":true}]]

我想更新取值并将其设置为 bookid 的 false。

   tmp = await User.findOneAndUpdate({id: req.body.id},  { $elemMatch: {'userObj.bookid': req.body.bookid }, { $set: { 'userObj.taken': false }, }, { new: true } )

您需要使用位置运算符

db.collection.update({
  id: 1,
  "userObj.bookid": 1
},
{
  $set: {
    "userObj.$.taken": false //$ is a positional operator which updates the matching array element
  },
  
})

Playgroun