在MongoDB中替换数组中的嵌入式文档 [英] Replacing embedded document in array in MongoDB

查看:77
本文介绍了在MongoDB中替换数组中的嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来替换数组中的整个嵌入式文档? 说要替换:

Is there an easy way to replace an entire embedded document in an array? Say replacing:

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

具有:

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

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

Searching for _id (embedded). Or do I need to replace each field individually using $set?

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

推荐答案

您正在使用对象数组"模式.您可以使用位置运算符,它看起来应该像这样:

You are using the "array of objects" pattern. You can use the positional operator, it should look something like this:

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

根据我的经验,如果对象具有自然ID,则对象数组"模式不是最佳的.在您的情况下,可以将其建模为以下形式:

In my experience, the "array of objects" pattern is not optimal if the objects have a natural ID. In your case, this could be modeled as the following:

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

在这种情况下,您可以使用点符号轻松进行操作更新所需的项目.

In this case you can use the dot notation to easily update the item you want.

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

这篇关于在MongoDB中替换数组中的嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆