我试图阻止我的 Mongo DB 集合中的重复项,但它们仍在进入。我正在从 twitter 读取数据并将其存储为:
var data = {
user_name: response[i].user.screen_name,
profile_image: response[i].user.profile_image_url,
content: {
text: response[i].text
},
id: response[i].id_str,
};
我有以下方法来阻止任何重复:
db[collection].ensureIndex( { id: 1, "content.text": 1 }, { unique: true, dropDups: true } );
id 字段正常工作,没有出现重复项,但“content.text”字段不起作用,并且出现重复项。有什么想法吗?
最佳答案
当您强制执行 unique 时对于复合索引的约束,仅当两个文档的 id
和 context.text
字段具有相同的值而不是单独的任一键时,两个文档才被视为相同。
要分别对字段 id
和 context.text
强制执行唯一约束,您可以按如下方式强制执行:
db.col.ensureIndex({"id":1},{unique:true})
对于其他字段也是如此。
关于node.js - MongoDB 确保索引不会停止重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28029691/