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

Deleting Documents With a Specific Count of Keys from MonogDB

我有用户的 collection,我想从中删除只有 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}, ...}) 但我觉得这个问题很荒谬。我还必须在 collection.

中找到所有字段

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

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

_id 键始终存在,因此您要查找的只是测试另一个字段是否存在。文档的总数 "field count" 为 2。如:

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

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