[英]How to update array in MongoDB?
我的收藏中大约有40份文件。 我需要更新两个数组中的某些元素。 文档的数组看起来像
"array1": [
{
"id" : "2030170",
"date1" : ISODate("2016-01-04T07:10:00.000Z"),
"date2" : ISODate("2016-01-04T08:00:00.000Z")
}
],
"array2": [
{
"Id" : "43463565",
"date1" : ISODate("2016-01-04T07:10:00.000Z"),
"date2" : ISODate("2016-01-04T08:00:00.000Z")
}
]
如何更新两个数组中的date1和date 2字段?
我也在使用Java脚本更新其他数据。 看起来像
db.getCollection('my.collec').update({ "myId" : { $gte: 293, $lte: 438}},
{
"$currentDate": { "time1": true },
"$set": {
"time2": true,
"time3": true
}
}, { multi: true }
)
我正在尝试这种方式:
db.getCollection('my.collec').update({ "myId" : { $gte: 293, $lte: 438}},
{
"$currentDate": { "time1": true },
"$set": {
"time2": true,
"time3": true,
"array1.0.date1": true,
"array1.0.date2": true,
"array2.0.date1": true,
"array2.0.date2": true
}
}, { multi: true }
)
但是,我得到的不是“ currentDate”,而是“ true”。 使用像时间这样的变量,一切正常。
我想知道为什么所有文档都没有放在一个数组中? 无论如何,请尝试:
db.YOURCOLLECTION.update(
{$and: [
{ date1: {$lt: $currentDate}},
{ date2: {$lt: $currentDate}}
]
},
{
date1 : $currentDate,
date2 : $currentDate
},
{upsert: true}
)
编辑:我注意到$ currentDate的一件事,我认为$ currentDate不会自动转换为ISO,因此您需要在上面的更新表达式中显式输入所需的时间戳记(根据上述绅士的说法),用$ ISO的值替换$ currentDate或使用转换库。
参见: https : //docs.mongodb.org/manual/reference/operator/update/currentDate/
我需要更新某些数组中的某些元素
知道标准是什么会很高兴
如何更新两个数组中的date1和date 2字段,以使这些字段不会添加到没有它们的对象中?
假设您仅更新array1和array2第一个元素
db.josef.update({
"array1": {
$size: 1
},
"array2": {
$size: 1
}
},
{
$set: {
"array1.0.date1": ISODate("2011-01-01T00:00:00.0000Z"),
"array1.0.date2": ISODate("2011-01-01T00:00:00.0000Z"),
"array2.0.date1": ISODate("2011-01-01T00:00:00.0000Z"),
"array2.0.date2": ISODate("2011-01-01T00:00:00.0000Z")
}
},
{
multi: true
})
如何更新两个数组中的date1和date 2字段,以使这些字段不会添加到没有它们的对象中?
默认情况下,upsert为false,因此不会添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.