gpt4 book ai didi

node.js - 从项目数组中设置增量值

转载 作者:太空宇宙 更新时间:2023-11-03 23:20:18 27 4
gpt4 key购买 nike

如何更新MongoDB中的多个文档并按升序设置元素的值?

我得到的文件如下

{
"_id" : ObjectId("5b162a31dfaf342dc44c920d")
}
{
"_id" : ObjectId("5b162a31dfaf342dc44c920f")
}
{
"_id" : ObjectId("5b162a31dfaf342dc44c920c")
}

如何使用单个查询更新整个文档,以便我可以在每个字段中按升序排列一个名为“order”的新元素,如下所示

{
"_id" : ObjectId("5b162a31dfaf342dc44c920d"),
"order": 1
}
{
"_id" : ObjectId("5b162a31dfaf342dc44c920f"),
"order": 2
}
{
"_id" : ObjectId("5b162a31dfaf342dc44c920c"),
"order": 3
}

目前我正在使用以下方式解决问题

   for(let i = 0; i <= req.body.id.length;i++) {

const queryOpts = {
_id: ObjectId(req.body.id[i])
};

const updateOpts = {
$set: {
'order': i + 1
}
};

const dataRes = await req.db.collection('GalleryImage').updateOne(queryOpts, updateOpts);

if(i === req.body.id.length-1) {
return commonHelper.sendResponseMessage(res, dataRes, {
_id: req.body.id
}, moduleConfig.message.updateGalleryOrder);


}

如果有大量文档,是否有比这更好的方法,这样就不会产生昂贵的操作?

最佳答案

使用bulkWrite()Array.map()构造语句:

try {
let response = await req.db.collection('GalleryImage').bulkWrite(
req.body.id.map((_id,order) =>
({ updateOne: {
filter: { _id: ObjectId(_id) },
update: {
$set: { order: order+1 }
}
}})
)
);
} catch(e) {
// deal with any errors
}

Array.map() 具有在其第二个函数参数内处理的数组元素的“索引”。因此,只需使用它来获取顺序并在所有语句上设置它即可。

与数据库写入/响应n次相比,这只需要发生“一次”

除了自己引入之外,没有其他方法可以得到“序列”,但至少我们可以用“一个”这样写,而不是几个。另请注意,使用 async/await 语法时要“捕获可能的错误”。

<小时/>

示例列表

const { MongoClient, ObjectID: ObjectId } = require('mongodb');

const uri = 'mongodb://localhost:27017';

const data = [
"5b162a31dfaf342dc44c920d",
"5b162a31dfaf342dc44c920f",
"5b162a31dfaf342dc44c920c"
];

const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {

try {

const client = await MongoClient.connect(uri);
let db = client.db('test');

// Set up
await db.collection('gallery').removeMany({});
await db.collection('gallery').insertMany(
data.map(_id => ({ _id: ObjectId(_id) }))
);

// Update with indexes
let response = await db.collection('gallery').bulkWrite(
data.map((_id,idx) =>
({
updateOne: {
filter: { _id: ObjectId(_id) },
update: { $set: { order: idx+1 } }
}
})
)
);

log({ response });

let items = await db.collection('gallery').find().toArray();
log({ items });

client.close();

} catch(e) {
console.error(e)
} finally {
process.exit()
}

})()

和输出

{
"response": {
"ok": 1,
"writeErrors": [],
"writeConcernErrors": [],
"insertedIds": [],
"nInserted": 0,
"nUpserted": 0,
"nMatched": 3,
"nModified": 3,
"nRemoved": 0,
"upserted": [],
"lastOp": {
"ts": "6563535160225038345",
"t": 18
}
}
}
{
"items": [
{
"_id": "5b162a31dfaf342dc44c920d",
"order": 1
},
{
"_id": "5b162a31dfaf342dc44c920f",
"order": 2
},
{
"_id": "5b162a31dfaf342dc44c920c",
"order": 3
}
]
}

正如预期的那样,清楚地显示了 nMatched: 3nModified: 3

关于node.js - 从项目数组中设置增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50694439/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com