Node.js mongodb查询数组中引用的对象

Node.js mongodb查询数组中引用的对象,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在nodejs中使用猫鼬。我正在尝试查询一些包含由引用对象组成的列表的字段。我创建了两个模式 飞行员 var PilotSchema = new mongoose.Schema({ races: [{type: mongoose.Schema.Types.ObjectId, ref: 'Race'}], }); 比赛 var RaceSchema = new mongoose.Schema({ start_ms: Number, }); 这里我只写了相关的字段 在比赛模式中

我在nodejs中使用猫鼬。我正在尝试查询一些包含由引用对象组成的列表的字段。我创建了两个模式

飞行员

var PilotSchema = new mongoose.Schema({
    races: [{type: mongoose.Schema.Types.ObjectId, ref: 'Race'}],
});
比赛

var RaceSchema = new mongoose.Schema({
    start_ms: Number,
});
这里我只写了相关的字段

在比赛模式中,我有一个键
start_ms
,它以毫秒为单位指示比赛开始的日期,在PilotSchema
races
字段中,我保存了对许多比赛的引用

我想做的是:

  • 以毫秒为单位记录未来的日期(my_date)
  • 检索间隔内没有比赛的所有飞行员(我的日期-2小时,我的日期+2小时)
我试着做一个例子来更好地解释

我的日期:2020年2月23日-12:00:00(毫秒)

在pilot字段
races
中,我有许多关于
RaceSchema
的参考,在每个参考对象中都有比赛开始的时间

现在查询Pilots集合,我想检索他们
比赛
字段中没有在(
2020年2月23日-10:00:00-2020年2月23日-14:00:00)期间开始的比赛的所有飞行员

我尝试使用此查询,但不起作用

races: {$not:
  {$elemMatch: 
    {start_ms: 
      { "$gt" : min_time, "$lt" : max_time }
    }
  }
}
在哪里


实际上我不知道怎么做,我看到在一段时间内检索一个数字,我可以使用
$gt
$lt
,但我不知道如何查询一组符合此特定条件的引用对象。

您必须为此编写一个聚合查询,从
pilot
中查找您的
比赛参考
&根据您的情况筛选它们

 Pilot.aggregate([
            {
                $lookup:{
                    from:'races',
                    localField:'races',
                    foreignField:'_id',
                    as:'races'
                }
            },{
                $unwind:'$races'
            },
            {
                $match:{
                    'races.start_ms':{
                        "$gt" : min_time, "$lt" : max_time
                    }
                }
            },{
                $group:{
                    _id:'$_id',
                    name:{$first:'$name'}
                }
            }
        ]);
假设您的
pilot
模式中有
name
,您可以通过编写此查询来获取所有此类
pilots
的列表

 Pilot.aggregate([
            {
                $lookup:{
                    from:'races',
                    localField:'races',
                    foreignField:'_id',
                    as:'races'
                }
            },{
                $unwind:'$races'
            },
            {
                $match:{
                    'races.start_ms':{
                        "$gt" : min_time, "$lt" : max_time
                    }
                }
            },{
                $group:{
                    _id:'$_id',
                    name:{$first:'$name'}
                }
            }
        ]);