如何更新数组内的特定值-MongoDB

时间:2019-12-18 08:17:22

标签: mongodb mongodb-query

我有一个mongodb集合用户,看起来像这样:

{
    "_id" : ObjectId("5dba8987b4a39c13bc104a23"),
    "contact" : {
        "firstName" : "Mark",
        "lastName" : "Doe",
        "parentsBloodType" : [ 
            {
                "type" : "AB+",
            }, 
            {
                "type" : "A+",
            }, 
        ],
    },
    "createdAt" : ISODate("2019-10-31T07:13:11.278Z"),
    "updatedAt" : ISODate("2019-11-26T09:59:41.611Z")
}

我需要运行原始查询以将AB +更新为O-。我还想在更新之前检查它们是否匹配。

我尝试了此操作,但它向用户添加了一个额外的字段:

  db.getCollection('users').update(
    {"_id": ObjectId("5dba8987b4a39c13bc104a23")},
    {"$set" : { 'parentsBloodType.' + '0' + '. type' : "O-"}}
    )

2 个答案:

答案 0 :(得分:2)

此人将进行更新:

create table file
(id int, 
 parentid int, 
 name varchar(1024), 
 size int, 
 type char(1)
); 

您与此匹配的支票:

db.users.update(
   { "_id": ObjectId("5dba8987b4a39c13bc104a23") },
   { "$set": { 'contact.parentsBloodType.0.type' : "O-"} }
)

仅当类型db.users.update( { "_id": ObjectId("5dba8987b4a39c13bc104a23"), "contact.parentsBloodType.type": "AB+" }, { "$set": { 'contact.parentsBloodType.0.type': "AB+" } } ) 存在(在任何父项中)时,此选项才会更新文档。

或者,如果您要检查第一类型是否为AB+,请使用

AB+

但是,我认为您实际上是在寻找它:

db.users.update(
   {
      "_id": ObjectId("5dba8987b4a39c13bc104a23"),
      "contact.parentsBloodType.0.type": "AB+"
   },
   { "$set": { 'contact.parentsBloodType.0.type': "AB+" } }
)

无论哪个db.users.update( { "_id": ObjectId("5dba8987b4a39c13bc104a23") }, { "$set": { 'contact.parentsBloodType.$[p].type': "0-" } }, { arrayFilters: [{ "p.type": "AB+" }] } ) 都更新为AB+,无论它在数组中的位置如何。

答案 1 :(得分:0)

您可以使用the positional $ operator更新与查询文档匹配的第一个元素

db.getCollection('users').update(
  { "_id": ObjectId("5dba8987b4a39c13bc104a23"), "parentsBloodType.type": "AB+" },
  { "$set" : { 'parentsBloodType.$.type' : "O-" } }
)

请注意:

  
      
  • 位置$运算符充当与查询文档匹配的第一个元素的占位符,并且
  •   
  • 数组字段必须出现作为查询文档的一部分。
  •   

或者如果您要更新所有符合一个或多个数组过滤条件的元素,请使用the filtered positional operator $[]

db.students.update(
   { "_id": ObjectId("5dba8987b4a39c13bc104a23") },
   { $set: { "parentsBloodType.$[element].type" : "O-" } },
   { 
     arrayFilters: [ { "element.type": "AB+" } ]
   }
)
相关问题