gpt4 book ai didi

mongodb - 从子文档中删除所有 _id 字段

转载 作者:可可西里 更新时间:2023-11-01 10:01:13 27 4
gpt4 key购买 nike

我一直在使用 Mongoose 将大量数据插入到 mongodb 数据库中。我注意到,默认情况下,Mongoose 会向所有子文档添加 _id 字段,给我留下看起来像这样的文档(为简洁起见,我删除了许多字段 - 我还将每个数组缩减为一个条目,它们通常有更多)

{
"start_time" : ISODate("2013-04-05T02:30:28Z"),
"match_id" : 165816931,
"players" : [
{
"account_id" : 4294967295,
"_id" : ObjectId("51daffdaa78cee5c36e29fba"),
"additional_units" : [ ],
"ability_upgrades" : [
{
"ability" : 5155,
"time" : 141,
"level" : 1,
"_id" : ObjectId("51daffdaa78cee5c36e29fca")
},
]
},
],
"_id" : ObjectId("51daffdca78cee5c36e2a02e")
}

我已经找到了如何防止 Mongoose 默认添加这些(http://mongoosejs.com/docs/guide.html,请参阅选项:id),但是我现在有 9500 万条记录,所有子文档上都有这些无关的 _id 字段。我有兴趣找到删除所有这些字段的最佳方法(将 _id 保留在顶级文档中)。我最初的想法是在每个对象上使用一堆 for...in 循环,但这似乎效率很低。

最佳答案

可以使用更新操作删除 players._id,如下所示:

db.collection.update({'players._id': {$exists : 1}}, { $unset : { 'players.$._id' : 1 } }, false, true)

然而,它是not possible使用 positional operator在嵌套数组中。因此,一种解决方案是直接在我们的数据库上运行脚本:

var cursor = db.collection.find({'players.ability_upgrades._id': {$exists : 1}});

cursor.forEach(function(doc) {

for (var i = 0; i < doc.players.length; i++) {
var player = doc.players[i];
delete player['_id'];

for (var j = 0; j < player.ability_upgrades.length; j++) {
delete player.ability_upgrades[j]['_id'];
}
}

db.collection.save(doc);
});

将脚本保存到一个文件中,并以该文件作为参数调用mongo:

> mongo remove_oid.js --shell

关于mongodb - 从子文档中删除所有 _id 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552084/

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