在猫鼬中按_id值范围选择文档

时间:2019-04-26 04:23:55

标签: javascript node.js mongodb mongoose

我正在创建一个应用程序,允许用户从主表创建子表,他/她可以在其中指定要包含在子表中的行范围。

这是我的Subtable模型:

 // Imports
const mongoose = require('mongoose');
const timestamps = require('mongoose-timestamp');
// Setup
const Schema = mongoose.Schema;

const ViewSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  table: {
    type: mongoose.Types.ObjectId,
    required: true,
    ref: 'Table'
  },
  range: [
    [
      {
        start: { type: mongoose.Types.ObjectId, ref: 'Row' },
        end: { type: mongoose.Types.ObjectId, ref: 'Row' }
      }
    ]
  ],
  columns: {
    type: Object,
    required: true
  }
});

ViewSchema.plugin(timestamps);

module.exports = mongoose.model('View', ViewSchema);

我目前存储范围的开始行和结束行。

现在,我想知道是否可以选择仅在开始行之后和结束行之前插入的文档,因此我不必提取1000行的行并在客户端进行过滤

如果这不可能,那么我很想知道其他解决方案。

谢谢你!

1 个答案:

答案 0 :(得分:1)

一个非常幼稚的解决方案是使用$gt$lt运算符,如下所示:

RowModel.find({ _id: { $gt: ObjectIdOfTheStart, $lt: ObjectIdOfTheEnd } });

因此,这将返回所有ObjectId大于开始行且小于结束行的行。

有关$gt$lt的更多信息。

就像@the_mahasagar提到的那样,您必须使用诸如开始日期和结束日期之类的内容,查询ObjectId的操作也是如此,如Steve Ridout here所述。

警告,我不建议您这样做。您应该使用其他某种标识符来查询这些行。

相关问题