mongo结果与唯一字段不一致 [英] Inconsistent mongo results with unique field

查看:74
本文介绍了mongo结果与唯一字段不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定何时会出现此问题,但我无法始终如一地从mongo中获取项目.我在数据库中有4000多个项目.这是架构.

Not sure when this issue cropped up but I am not able to fetch items from mongo consistently. I have 4000+ items in the db. Here's the schema.

var Order = new Schema({
 code: {
  type: String,
  unique: true
},
...
});

现在运行一些查询:

Order.find().exec(function(err, orders) {
 console.log(orders.length); // always 101 
})

Order.find().limit(100000).exec(function(err, orders) {
 console.log(orders.length); // varies, sometimes 1150, 1790, 2046 - never more
})

现在,如果我从架构中删除"unique:true",它将始终返回总金额:

Now if I remove the 'unique: true' from schema it will always return the total amount:

Order.find().exec(function(err, orders) {
 console.log(orders.length); // always 4213 (correct total)
})

关于为什么会发生这种行为的任何想法吗? afaik的代码都是唯一的(来自商人的订单).在3.8.6、3.8.8上进行了测试

Any idea as to why this behavior occurs? afaik the codes are all unique (orders from a merchant). This is tested on 3.8.6, 3.8.8

推荐答案

好的问题确实是唯一索引不存在/已损坏.我后来在游戏中添加了唯一索引,这很内gui,可能已经有些笨拙了,从而阻止了Mongo创建索引.

Ok issue was indeed unique index being not there/corrupted. I a guilty of adding the unique index later on in the game and probably had some dups already which prevented Mongo from creating indexes.

我删除了重复项,然后在mongo shell中执行了以下操作:

I removed the duplicates and then in the mongo shell did this:

db.orders({name: 1}, {unique: true, dropDubs: true});

我认为上面的方法可以消除公仔,但由于公仔而死亡.我敢肯定有一种shell方法可以做到这一点,但是我只是用一些js代码做到了,然后运行上面的代码来重新创建可以用以下方法验证的索引:

I would think the above would remove dups but it would just die because of the dups. I am sure there is a shell way to do this but I just did it with some js code then ran the above to recreate the index which can be verified with:

db.orders.getIndexes()

这篇关于mongo结果与唯一字段不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆