英文:
How can I add each record to the sequence number in mongosh?
问题
我使用 MongoDB 6.0。
我只是尝试在 mongosh 中更新每个字段的顺序号。
我想要修改字段并更新集合。
sequence_number
将从随机数中获得。
以下是示例:
{
"_id": "1",
"name": "Ken"
},
{
"_id": "2",
"name": "Ryu"
}
我想要做的是这样的:
{
"_id": "1",
"name": "Ken",
"sequence_number": "10"
},
{
"_id": "2",
"name": "Ryu",
"sequence_number": "11"
}
有人可以帮助我吗?
谢谢。
我阅读了这个问题。
https://stackoverflow.com/questions/67726809/how-can-i-add-a-new-field-from-another-one-value
但方法略有不同。
英文:
I use MongoDB 6.0.
And I'm just trying to update each field with sequence number in mongosh.
I want the field modified and update the collection.
The sequence_number
will be given from random number.
Here's the example:
{
_id: "1",
name: "Ken"
},
{
_id: "2",
name: "Ryu"
}
And what I want to do is this:
{
_id: "1",
name: "Ken",
sequence_number: "10"
},
{
_id: "2",
name: "Ryu",
sequence_number: "11"
}
Does anyone help me?
Thanks.
I read the question.
https://stackoverflow.com/questions/67726809/how-can-i-add-a-new-field-from-another-one-value
But the approach is a little different.
答案1
得分: 1
你可以迭代集合中的所有文档,并对每个文档调用 updateOne
。
let sequenceCounter = 10;
db.users.find().forEach((user) => {
db.users.updateOne(
{ _id: user._id },
{
$set: {
sequence_number: sequenceCounter.toString()
}
});
sequenceCounter++;
});
如果集合包含大量文档,请考虑使用 bulkWrite()
批处理操作。
let sequenceCounter = 10;
const bulkOperations = db.users.find().toArray().map((user) => {
return {
updateOne: {
filter: { _id: user._id },
update: { $set: { sequence_number: (sequenceCounter++).toString() } }
}
}
});
db.users.bulkWrite(bulkOperations);
如果您希望在插入文档时生成 sequence_numbers
,请考虑阅读 https://www.mongodb.com/basics/mongodb-auto-increment。MongoDB 没有内置的自动递增功能。此方法使用一个 counter
集合和在创建新文档时触发的 JavaScript 函数。
英文:
You can iterate over all documents in collection and call updateOne
for each of them.
let sequenceCounter = 10;
db.users.find().forEach((user) => {
db.users.updateOne(
{ _id: user._id },
{
$set: {
sequence_number: sequenceCounter.toString()
}
});
sequenceCounter++;
});
If collection contains large number of documents consider batching the operations with bulkWrite()
.
let sequenceCounter = 10;
const bulkOperations = db.users.find().toArray().map((user)=>{
return {
updateOne: {
filter: { _id: user._id },
update: { $set: { sequence_number: (sequenceCounter++).toString() } }
}
}
})
db.users.bulkWrite(bulkOperations);
If you are interested in generating the sequence_numbers
during insertion of documents, consider reading https://www.mongodb.com/basics/mongodb-auto-increment. Mongodb does not have auto increment functionality built in. This approach uses a counter
collection and js functions that are triggered when creating new documents.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论