如何使用 mongoDB 更新操作进行用户内部查询?
How to user inner query with mongoDB update operation?
我正在尝试编写更新查询来更新 column/filed 的 collection。我的 collection 有 4 个字段:_id、名称、日期 1、日期 2。
我正在尝试编写一个更新查询来设置 date1 = date2,我尝试使用如下所示的内部查询,但没有成功。
db.myCollection.updateMany(
{},
{
'$set':
{
'date2': db.myCollection.find({},{date1:1, _id:0}).limit(1)
}
}
);
可能是这样的(版本 4.2+):
db.collection.update({},
[
{
$addFields: {
date1: "$date2"
}
}
],
{
multi: true
})
对于您的情况(版本 3.6):
db.collection.find().forEach(
function (elem) {
db.collection.update(
{
_id: elem._id
},
{
$set: {
date1: elem.date2
}
}
);
}
);
var cursor = db.collection.find()
var requests = [];
cursor.forEach(document => {
requests.push( {
'updateOne': {
'filter': { '_id': document._id },
'update': { '$set': { 'date1': document.date2 } }
}
});
if (requests.length === 500) {
//Execute per 500 operations and re-init
db.collection.bulkWrite(requests);
requests = [];
}
});
if(requests.length > 0) {
db.collection.bulkWrite(requests);
}
我正在尝试编写更新查询来更新 column/filed 的 collection。我的 collection 有 4 个字段:_id、名称、日期 1、日期 2。
我正在尝试编写一个更新查询来设置 date1 = date2,我尝试使用如下所示的内部查询,但没有成功。
db.myCollection.updateMany(
{},
{
'$set':
{
'date2': db.myCollection.find({},{date1:1, _id:0}).limit(1)
}
}
);
可能是这样的(版本 4.2+):
db.collection.update({},
[
{
$addFields: {
date1: "$date2"
}
}
],
{
multi: true
})
对于您的情况(版本 3.6):
db.collection.find().forEach(
function (elem) {
db.collection.update(
{
_id: elem._id
},
{
$set: {
date1: elem.date2
}
}
);
}
);
var cursor = db.collection.find()
var requests = [];
cursor.forEach(document => {
requests.push( {
'updateOne': {
'filter': { '_id': document._id },
'update': { '$set': { 'date1': document.date2 } }
}
});
if (requests.length === 500) {
//Execute per 500 operations and re-init
db.collection.bulkWrite(requests);
requests = [];
}
});
if(requests.length > 0) {
db.collection.bulkWrite(requests);
}