简体   繁体   English

如何设置数组中特定对象的属性? mongodb

[英]How to set an property of a specific object in an array? mongodb

I have a mongodb document, for a project object: 我有一个mongodb文档,用于project对象:

{
  members: [
    { _id: ObjectId(1), 
      active: true },
    { _id: ObjectId(2),
      active: false }
  ]
}

I'd like to change project.members[1].active = true , while only knowing ObjectId(2) during the initial query. 我想更改project.members[1].active = true ,而仅在初始查询期间知道ObjectId(2) Is there a way to do this without using findOne and manually looping over the members array and checking for equivalence of the ObjectId? 有没有一种方法,而无需使用findOne并手动循环遍历成员数组并检查ObjectId的等效性?

This works. 这可行。 The stuff after this section may work in the future. 本节之后的内容将来可能会起作用。

Using http://docs.mongodb.org/manual/reference/operator/update/positional/ , I figured it out. 使用http://docs.mongodb.org/manual/reference/operator/update/positional/ ,我知道了。

db.collection('projects').findAndModify(
  {                                                          // Query
    "_id": ObjectId(id),
    "members._id": ObjectId(user_id) 
  },
  [[]],                                                      // Ordering
  {                                                          // Update parameters
    $set: { "members.$.active": true }
  }, 
  {new: true},                                               // Options
  function(err, project) {
    // do stuff
});

Since the $ positional operator selects the first query match, it'll $set the active property for only that object in the array. 由于$位置运算符选择了第一个查询匹配项,因此它将仅为数组中的该对象$set active属性。

UPDATE: The following won't work... yet. 更新:以下内容将无法使用...。 $pull and $push cannot be used simultaneously currently, but is under consideration . $pull$push当前不能同时使用,但正在考虑中

"err": "Field name duplication not allowed with modifiers"

I think I can use a $pull and a $push to achieve what I need. 我想我可以使用$pull$push来实现所需的功能。

db.collection('projects').findAndModify(
  {                                                          // Query
    "_id": ObjectId(id),
    "members": { $elemMatch: { _id: ObjectId(user_id) } } },
  [[]],                                                      // Ordering
  {                                                          // Update parameters
    $pull: { "members": { $elemMatch: { _id: ObjectId(user_id) } } }, 
    $push: { "members": ObjectId(user_id), active: true }
  }, 
  {new: true},                                               // Options
  function(err, project) {
    // do stuff
});

The "members" line of the query is optional - adding this line will restrict the update so that only users already in the members array can get changed. 查询的“成员”行是可选的-添加此行将限制更新,以便仅更改已在members数组中的用户。 If it is removed, then running this will overwrite or create a new member. 如果将其删除,则运行该命令将覆盖或创建一个新成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM