问题描述
精确匹配子文档很容易,但是有没有办法精确匹配集合中的整个文档?
Exact matching subdocuments is easy, but is there a way to exact match entire document in a collection ?
我有很多类似数据的文档,我只需要完全匹配,不需要额外的数据
I have a lot of documents with similar data, and I only need exact matches with no extra data
使用负 $exists 对我不起作用,因为我事先不知道所有可能的字段.
Using negative $exists will not work for me, as I dont know all the possible fields beforehand.
推荐答案
我不认为这是完全可能的,但一个可能的解决方案是散列文档.
i don't think this is possible outright, but a possible solution is to hash the document.
保存时,总是创建文档的哈希:
when saving, always create a hash of the document:
var doc = {};
delete doc.hash; // never include the hash itself in the calculation
doc.hash = crypto.createHash('sha256').update(JSON.stringify(doc)).digest();
db.collection.insert(doc);
那么在查询的时候就可以通过hash来查询了:
Then when querying, you can query by hash:
db.collection.find({
hash: hash
})
如果您经常对文档进行原子更新,可能会很烦人.
might be annoying if you frequently do atomic updates on the document.
这篇关于如何精确匹配整个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!