Mongodb Mongo:字段的$exists上的索引

Mongodb Mongo:字段的$exists上的索引,mongodb,mongoose,mongodb-query,mongodb-indexes,mongoose-plugins,Mongodb,Mongoose,Mongodb Query,Mongodb Indexes,Mongoose Plugins,我有以下猫鼬模式: var dataSchema = new Schema({ owner: { type: Schema.ObjectId, ref: 'User' }, time : { type: Date, default: Date.now }, eventCount:Number }); 对于某些数据对象,eventCount已定义且为正数;对于其他数据对象,eventCount未定义。我想设计一个索引,使这样的查询尽可能快: db.data

我有以下猫鼬模式:

var dataSchema = new Schema({  
    owner: { type: Schema.ObjectId, ref: 'User' },  
    time : { type: Date, default: Date.now },  
    eventCount:Number  
});
对于某些数据对象,eventCount已定义且为正数;对于其他数据对象,eventCount未定义。我想设计一个索引,使这样的查询尽可能快:

db.datacollection.find({owner: <some ID>, eventCount: {$exists:true}, time: {<some time range>})
然后建立一个这样的索引

db.datacollection.ensureIndex({user:1, isEventCount: 1, time:1})
db.datacollection.find({owner: <some ID>, isEventCount: true, time: {<some time range>})
然后像这样运行我的查询

db.datacollection.ensureIndex({user:1, isEventCount: 1, time:1})
db.datacollection.find({owner: <some ID>, isEventCount: true, time: {<some time range>})
db.datacollection.find({owner:,isEventCount:true,time:{})
这种方法有几个缺点,即:

  • 我正在数据库中保存冗余信息
  • 我必须编写额外的中间件代码来实现这一点
  • 我必须修改数据库中的现有条目

  • 是否有人知道有更好的解决方案或库可以对此提供帮助?

    您无需通过所有这些来获得良好的查询性能。使用现有查询:

    db.datacollection.find({owner: <some ID>, eventCount: {$exists:true}, time: {<some time range>}
    
    在大多数情况下,都应该提供相当好的性能。显然,我不知道现有数据集的大小或分布情况,但我认为需要创建一个
    isEventCount
    标志,这对您来说是非常不寻常的

    一般来说,在MongoDB中对模式设计采取任何不寻常的措施之前,我将执行以下操作:

    1) 设置具有合理容量的测试数据 2) 使用explain()尝试您的查询

    它将让您非常清楚查询的性能以及如何/何时使用索引


    我尝试了这个。这不起作用。假设我有以下数据:{owner:UserA,dataCount:1,时间:昨天}{owner:UserA,dataCount:1,time:lastYear}-假设有1000000条类似于这样的记录{owner:UserA,dataCount:2,time:treaty}您上面描述的索引将按照我上面描述的方式对记录进行排序。然后,如果我要运行查询:find({owner:UserA,eventCount:{$exists:true},time:{从昨天开始}}),光标将必须扫描去年的所有记录。“不起作用”表示查询失败?或者您不喜欢性能?您可以从索引中删除时间字段-正如我所说,我不知道数据的大小和分布,只有您知道。关键是您不需要计算字段“isEventCount”。在任何情况下,您都应该对各种方法进行基准测试,以了解哪些方法对您有效-没有一种模式/索引方法适用于所有人和所有用例。与中不同的是,我不喜欢性能。我希望设计索引时,对于此特定查询,我希望
    nscanned
    的对象数等于ound.使用我建议的方案是可能的,而使用你的方案是不可能的。(以下玩具数据集就是这种情况:
    {“datacount”:1,“time”:ISODate(“2013-06-10T15:29:32.603Z”),“exists”:true}{“datacount”:2,“time”:ISODate(“2014-06-10T15:29:32.603Z”),“exists”:true}{“datacount”:1,“time”:ISODate(“2014-06-10T15:29:32.603Z”),“exists”:true}