【问题标题】:mongodb find array of object and updatemongodb查找对象数组并更新
【发布时间】:2018-05-22 21:29:12
【问题描述】:

我的数据库中有这种格式

[{
  "birth-date": "18/12/2010",
  "babies": [{
    "id":1,
    "name": "James",
    "age": 8,
  }, {
    "id":2,
    "name": "John",
    "age": 4,
  }]
}]

所以我想将 James 的名字更新为其他名称。我愿意

Babies.update({"birth-date":date, 'babies.id': 1}, {'$set': {'babies.$.name':"something else"}}, function(err, response){
        res.json(response);
  })

它返回 ok:0 第二个选择器 ('babies.id': 1) 有问题。

【问题讨论】:

  • 我不知道 mongoose,但是在 mongo shell 中Babies.update({"birth-date", 'babies.id': 1},... 会报错因为"birth-date" 需要:某事,即该属性需要一个密钥(例如Babies.update({"birth-date":"18/12/2010", 'babies.id': 1},...
  • @RafaelCaballero 更新了我的答案,只是错字。
  • 你可以尝试用 '$set' 替换 set 部分:{'babies.$.name':"something else"} 吗?
  • @SagarReddy 试过了,不行。
  • 你是否错过了 set 的结束卷曲?

标签: node.js mongodb express mongoose


【解决方案1】:

您可以使用$and 选择器进行此调用;

Babies.update({
      $and: [{
        'birth-date': date
      },
      {
        'babies': {
          $elemMatch: {
            'id': id_you_are_searching
          }
        }
      }
      ]
    },
      {$set: {'babies.$.name':"something else"}}, function(err, response){
        res.json(response);
  })

【讨论】:

    【解决方案2】:

    要根据某些数组属性匹配文档,您需要 $elemMatch

    Babies
      .update({ babies: {$elemMatch:{id : 1}} }, {'$set': {name:"something else"}, function(err, response){
            res.json(response);
      })
    

    看看这个: https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch/

    【讨论】:

    • 这只是单一条件。我需要日期和婴儿身份证。
    • 您可以轻松添加任意数量的条件,就像任何其他查询一样。婴儿 .update({ 婴儿: {$elemMatch:{id : 1}}, 'birth-date': "18/12/2010"}, {'$set': {name:"something else"}, function(错误,响应){ res.json(响应);})
    • $elemMatch 在这里不需要。当您需要多个条件时使用它。如果你只需要平等,就像你的情况一样,'babies.id':1 是完美的,事实上,我已经在 mongo db.collection.update({"birth-date":"18/12/2010", "babies.id":1}, {'$set':{name:'something'}}) 中尝试过,它工作正常,collection 包含你的文档。
    • @RafaelCaballero 问题是我没有选择正确的目标。
    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多