Mongodb 更新所有具有唯一 id 的文档 [英] Mongodb update all the documents with unique id
问题描述
我有一个名为 products
的集合,其中包含近 10 万个文档.我想引入一个名为 secondaryKey
的新键,它具有唯一值 uuid
在所有文件中.我使用 nodejs
来做到这一点.
I have collection with name products
with almost 100k documents. I want to introduce a new key called secondaryKey
with unique value uuid
in all the documents.
I do this using nodejs
.
我面临的问题:-
当我尝试以下查询时,
db.collection('products').updateMany({},{"$set":{secondaryKey: uuid()}});
这里更新所有具有相同uuid
值的文档,
Here it updates all the documents with same uuid
value,
我尝试使用循环逐个更新文档,但这里的问题是我在 updateOne
中没有 filter
值,因为我想更新所有文档.
I try with loop to update document one by one,but here issues is I don't have filter
value in updateOne
because I want to update all the documents.
任何人都可以在这里帮助我.谢谢:)
Can anyone please help me here. Thanks :)
推荐答案
如果你使用的是 MongoDB 版本 >= 4.4 你可以试试这个:
If you are using MongoDB version >= 4.4 You can try this:
db.products.updateMany(
{},
[
{
$set: {
secondaryKey: {
$function: {
body: function() {
return UUID().toString().split('"')[1];
},
args: [],
lang: "js"
}
}
}
}
]
);
输出
[
{
"_id": ObjectId("..."),
"secondaryKey": "f41b15b7-a0c5-43ed-9d15-69dbafc0ed29"
},
{
"_id": ObjectId("..."),
"secondaryKey": "50ae7248-a92e-4b10-be7d-126b8083ff64"
},
{
"_id": ObjectId("..."),
"secondaryKey": "fa778a1a-371b-422a-b73f-8bcff865ad8e"
}
]
这篇关于Mongodb 更新所有具有唯一 id 的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!