MongoDB Bulk.find.update() 不修改数组对象,只添加新的
MongoDB Bulk.find.update() not modifying array objects, only adding new ones
我对 MongoDB $set & $-operators 有疑问。我尝试修改现有数组
我的更新方法大概是这样的(我无法获得 Clojure/Monger 中所写的确切副本):
bulk.find({
_id: 2,
channelStatuses.channel: {$eq: "BAR"}
}).update({
$set: {"channelStatuses.$.status": "error" }
});
我的数据看起来像这样:
{
"_id" : "1",
"channelStatuses" : [
{
"channel" : "FOO",
"status" : "done"
}
]
},
{
"_id" : "2",
"channelStatuses" : [
{
"channel" : "BAR",
"status" : "done"
}
]
},
{
"_id" : "3",
"channelStatuses" : [
{
"channel" : "BAZ",
"status" : "error"
}
]
},
{
"_id" : "3",
"channelStatuses" : []
}
所以我想要它做的是修改 _id = 2 的文档的 channelStatuses 对象的状态。
而是在 channelStatuses 数组中创建一个新对象,文档如下所示:
{
"_id" : "2",
"channelStatuses" : [
{
"channel" : "BAR",
"status" : "done"
},
{
"channel" : "BAR",
"status" : ""
}
]
},
所以我发现您的查询有几个问题。
在您的文档中,_id
字段是文本值,但在查询中您将其用作数字。
在您的查询中 channelStatuses.channel: {$eq: "BAR"}
无效。 JSON 键不能有 .
除非你用双引号转义。
你可以将channelStatuses.channel: {$eq: "BAR"}
简化为"channelStatuses.channel": "BAR"
现在尝试以下查询,看看它是否有效。
var bulk = db.doc.initializeUnorderedBulkOp();
bulk.find({
_id: "2",
"channelStatuses.channel": "BAR"
}).update({
$set: {"channelStatuses.$.status": "error" }
});
bulk.execute();
它应该只更新现有字段。请参阅下面的最终输出
{
"_id" : "1",
"channelStatuses" : [
{
"channel" : "FOO",
"status" : "done"
}
]
}
{
"_id" : "2",
"channelStatuses" : [
{
"channel" : "BAR",
"status" : "error"
}
]
}
{
"_id" : "3",
"channelStatuses" : [
{
"channel" : "BAZ",
"status" : "error"
}
]
}
我对 MongoDB $set & $-operators 有疑问。我尝试修改现有数组
我的更新方法大概是这样的(我无法获得 Clojure/Monger 中所写的确切副本):
bulk.find({
_id: 2,
channelStatuses.channel: {$eq: "BAR"}
}).update({
$set: {"channelStatuses.$.status": "error" }
});
我的数据看起来像这样:
{
"_id" : "1",
"channelStatuses" : [
{
"channel" : "FOO",
"status" : "done"
}
]
},
{
"_id" : "2",
"channelStatuses" : [
{
"channel" : "BAR",
"status" : "done"
}
]
},
{
"_id" : "3",
"channelStatuses" : [
{
"channel" : "BAZ",
"status" : "error"
}
]
},
{
"_id" : "3",
"channelStatuses" : []
}
所以我想要它做的是修改 _id = 2 的文档的 channelStatuses 对象的状态。
而是在 channelStatuses 数组中创建一个新对象,文档如下所示:
{
"_id" : "2",
"channelStatuses" : [
{
"channel" : "BAR",
"status" : "done"
},
{
"channel" : "BAR",
"status" : ""
}
]
},
所以我发现您的查询有几个问题。
在您的文档中,
_id
字段是文本值,但在查询中您将其用作数字。在您的查询中
channelStatuses.channel: {$eq: "BAR"}
无效。 JSON 键不能有.
除非你用双引号转义。你可以将
channelStatuses.channel: {$eq: "BAR"}
简化为"channelStatuses.channel": "BAR"
现在尝试以下查询,看看它是否有效。
var bulk = db.doc.initializeUnorderedBulkOp();
bulk.find({
_id: "2",
"channelStatuses.channel": "BAR"
}).update({
$set: {"channelStatuses.$.status": "error" }
});
bulk.execute();
它应该只更新现有字段。请参阅下面的最终输出
{
"_id" : "1",
"channelStatuses" : [
{
"channel" : "FOO",
"status" : "done"
}
]
}
{
"_id" : "2",
"channelStatuses" : [
{
"channel" : "BAR",
"status" : "error"
}
]
}
{
"_id" : "3",
"channelStatuses" : [
{
"channel" : "BAZ",
"status" : "error"
}
]
}