参见下面的示例(来自mongo厨师的json格式)。我需要向集合中的每个元素添加一个名为isReadOnly (bool)的新字段。我该怎么做?我可以轻松地将它添加到文档的根目录中,但在每个数组元素中都很难做到这一点。
{
"_id" : "fda42f22-0fa4-4e4a-94bf-245b1124c8b9",
"_t" : "FullConfiguration",
"DeviceConfigName" : "Illinois",
"Elements" : [
{
"_t" : "NumberConfigurationElement",
"AsciiConfigNumber" : NumberInt(10),
"DataType" : NumberInt(1),
"ByteOffset" : NumberInt(0),
"Name" : "alcohol_limit",
"Description" : "The alcohol limit of the device (ug/l)",
"AckResponse" : "HT-CONFG,010,00119",
"DevicePart" : NumberInt(1),
"Value" : NumberInt(119),
"DefaultValue" : NumberInt(119),
"Min" : NumberInt(50),
"Max" : NumberInt(500)
}, .....
发布于 2016-12-08 16:36:46
您可以这样做(如果您的集合名为“coll”):
db.coll.find().forEach(function(e) {
var t = e.Elements;
t.forEach(function(e) {
e.isReadOnly=false
});
db.coll.update({ _id : e._id }, { $set: { Elements : t } } );
})
发布于 2016-12-08 17:31:40
@Styvane,这就是我想出来的,看起来还是有点烦躁。
var query = {
Elements: {
$elemMatch: {
_t: { $exists: true },
isReadOnly: { $exists: false }
}
}
};
while (db.collection.find(query).count() > 0) {
db.collection.update(
query,
{ $set: { "Elements.$.isReadOnly": true } }
);
}
发布于 2019-12-20 13:10:51
@David我已经和MongoDB 3.6+合作解决了。
db.collection.update({},
{ $set: { "Elements.$[].isReadOnly": false } }, { multi: true }
)
此命令将在文档的所有isReadOnly = false
数组字段中添加Element
字段。
$position
修饰符指定$push
操作符插入元素的数组中的位置。没有$position
修饰符,$push
运算符将元素插入到数组的末尾。有关更多信息,请参见$push
修饰符。
您可以在位置操作符文档上找到更多细节
https://stackoverflow.com/questions/41044153
复制相似问题