简体   繁体   English

在子文档数组中插入新字段

[英]Inset a new field in an array of sub-document

I have the following schema: 我有以下架构:

{
   "name"    : "MyName",
   "actions" : [{
       "kind"   : "kind1",
       "result" : "result1"
   },
   {
       "kind":"kind1",
       "result":"result1"
   }
   ]
}

I want to insert a new field called 'expected' in different subdocument in actions. 我想在不同的子文档中插入一个名为“ expected”的新字段。 I tried the following command but I have an issue with it: 我尝试了以下命令,但是我遇到了问题:

db.tasks.update({},{$push:{ "actions.expected" : "MyExpected" }},false,true)
can't append to array using string field name expected

You can use the $addToSet functionality: 您可以使用$ addToSet功能:

http://docs.mongodb.org/manual/reference/operator/update/addToSet/ http://docs.mongodb.org/manual/reference/operator/update/addToSet/

Try 尝试

db.tasks.update({}, {$addToSet: {'actions.expected': 'MyExpected'}})

You have json object inside array but in the query you are trying to add string. 您在数组中有json对象,但是在查询中您尝试添加字符串。 Thats why you got an exception. 那就是为什么你有例外。 You can update your query as follows. 您可以按以下方式更新查询。

db.tasks.update({},{$push:{ "actions" : {"expected" : "MyExpected"} }},false,true)

Well, the problem is that you're trying to $push into an array, but the destination you're giving is not an array. 好吧,问题是您试图将$push到数组中,但是给出的目的地不是数组。

actions.expected is the expected field in the actions field, and you're pushing "MyExpected" into that array - but such an array does not exist. actions.expectedactions字段中的expected字段,您正在将"MyExpected"推入该数组-但是这样的数组不存在。

Let's assume you had the following data, perhaps that explains it best. 假设您具有以下数据,也许可以最好地解释它。 Your query would work on a data structure like this: 您的查询将在这样的数据结构上工作:

actions : { expected : [] } // actions is an object here
// ... {$push:{ "actions.expected" : "MyExpected" }}
actions : { expected : ["MyExpected"] }

Instead, you'll probably want to push an object into the actions array: 取而代之的是,您可能希望将一个对象推入actions数组:

actions : []
$push : { "actions" : { "expected" : "MyExpected" } }
actions : [ { "expected" : "MyExpected" } ]

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

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