【问题标题】:Replacing embedded document in array in MongoDB替换 MongoDB 中数组中的嵌入文档
【发布时间】:2012-03-01 07:20:43
【问题描述】:

有没有一种简单的方法可以替换数组中的整个嵌入文档? 说替换:

{
   "_id" : "2",
      "name" : "name2",
      "xyz..." : "xyz2..."
}

与:

{
   "_id" : "2",
      "name" : "name6",
      "xyz..." : "xyz5..."
      "morefields..." : "fields..."
}

正在搜索 _id(嵌入式)。还是我需要使用 $set 单独替换每个字段?

{
  "_id" : "2",
  "users" : [{
      "_id" : "1",
      "name" : "name1",
      "xyz..." : "xyz1..."
    }, {
      "_id" : "2",
      "name" : "name2",
      "xyz..." : "xyz2..."
    }],
  "name" : "main name"
}

【问题讨论】:

    标签: mongodb documents


    【解决方案1】:

    您正在使用“对象数组”模式。你可以使用positional operator,它应该看起来像这样:

    coll.update( {'_id':'2', 'users._id':'2'}, {$set:{'users.$':{ "_id":2,"name":"name6",... }}}, false, true)
    

    根据我的经验,如果对象具有自然 ID,则“对象数组”模式不是最佳的。在您的情况下,这可以建模如下:

    {
      "_id" : "2",
      "users" : 
        { "1" : { "name" : "name1", "xyz..." : "xyz1..." }, 
          "2" : { "name" : "name2", "xyz..." : "xyz2..." }
        }
      "name" : "main name"
    }
    

    在这种情况下,您可以使用dot notation 轻松更新您想要的项目。

    var newValue = {  "name" : "name6", "xyz..." : "xyz5...", "morefields..." : "fields..." };
    coll.update({_id: 2}, { $set: { "users.2" : newValue } });
    

    【讨论】:

    • 效果很好,谢谢!有趣的第二种选择,但我不确定它是否会起作用,因为我需要删除中间的一些条目。 “users.2”是我假设的数组中的位置。
    • 我以为 users.2 指的是数组位置,但它实际上使用的是 id(并为所有其他数组项返回空括号},很酷。
    • MongoDB 在查询中识别数组。所以users.2 可以搜索users 数组以查找具有key2 的对象 它可以查看key:2users
    • 我正在使用您的第二个模型,但现在我想我将无法索引内部名称字段。如果它是一个数组,它将是 users.name 但这里是 users.1.name users.2.name?
    • 你是对的,第二个结构的索引不是很好。这绝对是一个权衡。但是您无法使用 MongoDB 优化所有查询。如果您希望此查询快速,则必须权衡更新的便利性。
    猜你喜欢
    • 1970-01-01
    • 2014-06-02
    • 2022-01-17
    • 2018-05-09
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多