gpt4 book ai didi

javascript - 从 MongoDB 中删除具有特定键数的文档

转载 作者:可可西里 更新时间:2023-11-01 09:59:05 25 4
gpt4 key购买 nike

我有用户集合,我想从中删除只有 2 个字段的文档。我的一般架构是这样的:

{
_id: 1,
name: af,
city: asd,
transaction: 1,
transactions:[{
id:1,
product: mobile,
amount: 10
},
id:2,
product: tv,
amount: 23
}],
many-other-sub-docs:[],
}

我想删除只有 _idtransaction 字段存在但其他字段不存在的文档。

NOTE: I have around 30-40 fields.

删除这些文档的一种方法是指定查询中不应存在的所有字段以及仅应存在的字段。例如db.users.remove({_id:{$exists:true}, transaction:{$exists:true}, other_field1:{$exists:false}, other_field2:{$exists:false}, ...} )但我觉得这个问题很荒谬。此外,我还必须找到我的集合中的所有字段。

还有其他更简单的方法吗?

最佳答案

是的,有更好的方法来做到这一点。我不能向您保证出色的性能,但它可能不会比您现在所做的差多少。您使用 $where 的 JavaScript 评估.

_id 键始终存在,因此您所寻找的只是测试另一个字段的存在。文档的总“字段数”为 2。如:

db.collection.remove({
"transaction": { "$exists": true },
"$where": "return Object.keys(this).length == 2"
})

因此只需测试文档键数组的长度以获得预期值。

关于javascript - 从 MongoDB 中删除具有特定键数的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29073095/

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