将字段插入子文档数组中.意外行为
Insert field into an array of sub-documents. unexpected behaviour
我正试图在每个子文档数组中的每个子文档中插入一个新字段。我有一个半工作脚本,预期结果是将ordinal_number
插入到每个子文档中,但它似乎插入到集合中每个comments
数组的第一个子文档中。
db.posts.find({
"comments.ordinal_number":{"$exists":true}}).forEach(function(data){
for(var i = 0; i < data.comments.length; i++) {
db.posts.update(
{
"_id": data._id,
"comments.body": data.comments[i].body
},
{
"$set": {
"comments.$.ordinal_number":
1
}
},true,true
);
}
});
输出结果:
"link" : "cxzdzjkztkqraoqlgcru",
"author" : "machine",
"title" : "arbitrary title",
"comments" : [
{
"body" : "...",
"email" : "ZoROirXN@thUNmWmY.com",
"author" : "Foo bar",
"ordinal_number" : 1
},
{
"body" : "...",
"email" : "eAYtQPfz@kVZCJnev.com",
"author" : "Foo baz"
}
]
您需要循环光标和数组条目,然后使用$
运算符使用"批量"操作更新数组中的每个子文档,以获得最大效率。
var bulk = db.posts.initializeOrderedBulkOp();
var count = 0;
db.posts.find().forEach(function(doc) {
var nComments = doc.comments.length;
for (var i = 0; i < nComments; i++) {
bulk.find( {
'_id': doc._id,
'comments': { '$elemMatch': { 'email': doc.comments[i]['email'] } }
} ).update({
'$set': { 'comments.$.ordinal_number': 1 }
})
}
count++;
if(count % 200 === 0) {
// Execute per 200 operations and re-init
bulk.execute();
bulk = db.posts.initializeOrderedBulkOp();
}
})
// Clean up queues.
if (count > 0) bulk.execute();
请注意,批量API在2.6中是新的,因此如果您使用的是旧版本,则需要使用.update()
方法。
db.posts.find().forEach(function(doc) {
var nComments = doc.comments.length;
for (var i = 0; i < nComments; i++) {
db.posts.update(
{
'_id': doc._id,
'comments': { '$elemMatch': { 'email': doc.comments[i]['email'] } }
},
{ '$set': { 'comments.$.ordinal_number': 1 } }
)
}
})
相关文章:
- 意外结果,在 ASP.Net 中解析 JSON 对象的数组
- Javascript 数组反向函数意外行为
- 使用变量初始化数组:意外的令牌 +
- 在 JS 中短路空数组会产生意外结果:“[] ||真 == []'
- 推入数组会产生意外的结果
- JavaScript在数组内迭代数组的意外行为
- JavaScript数组-意外的令牌
- JavaScript:推送到空数组中的意外行为
- 意外的类型错误 - Javascript,多维数组
- 在用数组填充初始化的数组上使用数组映射的意外行为
- 切换句柄多维数组.意外结果
- 随后的多维数组排序会产生意外的结果
- 将数组项用作对象中的键时出现意外的令牌错误
- 从数组中拼接出意外的元素
- JavaScript中2D数组的值发生意外更改
- JavaScript 二维数组填充中的意外输出
- 将字段插入子文档数组中.意外行为
- AngularJS分析JSON数组对象意外的令牌:
- 意外标记d'当尝试将对象添加到Javascript对象数组时
- 数组参数解构抛出意外错误