Node.js 在更新中执行$set和$rename
我有以下文件 { “价值”:5 } 我希望更新会导致以下情况: { “价值旧”:5, “价值”:3 } 我试图通过以下更新查询来实现这一点Node.js 在更新中执行$set和$rename,node.js,mongodb,Node.js,Mongodb,我有以下文件 { “价值”:5 } 我希望更新会导致以下情况: { “价值旧”:5, “价值”:3 } 我试图通过以下更新查询来实现这一点 { $rename: {"value": "value_old"} }, { $set :{ "value": (wtv new value was sent to the function) 3 } 此代码似乎不起作用。。。。 我不想执行两个单独的更新查询 我尝试过聚合,并在
{
$rename: {"value": "value_old"}
},
{ $set :{
"value": (wtv new value was sent to the function) 3
}
此代码似乎不起作用。。。。
我不想执行两个单独的更新查询
我尝试过聚合,并在它的末尾加上$out,但这会导致删除整个集合,我只想更新单个文档
我这样做的原因是因为我需要原子操作。我刚刚阅读了db.eval(),它似乎很有希望,因为它可以锁定数据库的读写操作。有人知道如何使用db.eval()执行2次更新吗?如果使用MongoClient,可以异步处理这两次更新。例如:
const MongoClient = require('mongodb').MongoClient;
function updateDB (newVal) {
return MongoClient.connect(MONGODB_URL)
.then( (database) => {
return Promise.all([
database.collection('yourCollection').update({id: 123}, {$rename: {'value': 'value_old'}}),
database.collection('yourCollection').update({
$set: {'value': newVal}
})
])
.then(() => {
database.close(true);
})
.then(() => {
return `new value: ${newVal} has been updated in : ${whatever}`;
})
.catch((err) => {
database.close(true);
throw err;
});
})
}
这就是我所做的,只有当所有操作都完成时,才能安全地执行许多操作并关闭数据库。如果使用MongoClient,您可以以异步方式处理这两个操作。例如:
const MongoClient = require('mongodb').MongoClient;
function updateDB (newVal) {
return MongoClient.connect(MONGODB_URL)
.then( (database) => {
return Promise.all([
database.collection('yourCollection').update({id: 123}, {$rename: {'value': 'value_old'}}),
database.collection('yourCollection').update({
$set: {'value': newVal}
})
])
.then(() => {
database.close(true);
})
.then(() => {
return `new value: ${newVal} has been updated in : ${whatever}`;
})
.catch((err) => {
database.close(true);
throw err;
});
})
}
这就是我所做的,只有在所有操作完成后,才能安全地执行许多操作并关闭数据库。这可能很危险,因为无法保证这两个操作的顺序。您可能会在$rename之前完成$set。这可能很危险,因为无法保证这两个操作的顺序。您可能会在$rename之前完成$set。