聚合管道内部联接

时间:2019-09-15 15:31:39

标签: node.js mongodb mongoose

我在MongoDB中有一组文档,其中包含一系列子文档,并缩减了以下架构:

项目:

const itemSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    status: {
      type: String,
      enum: ['active','inactive','quarantine','deleted']
    },
    subitems: [{
      type: Schema.ObjectId,
      ref: 'subitem'
    }]

});

子项:

const subItemSchema = new Schema({
    parent: {
        type: Schema.Types.ObjectId,
        ref: 'item',
        required: true
    },
    status: {
        type: String,
        required: true,
        enum: ['active','inactive','deleted']
    },
    number: Number
});

我试图查询项目以找到具有一定数量的子项目,在MongoDB中,我可以执行以下操作:

[{$lookup: {
  from: 'subitems',
  localField: 'subitems',
  foreignField: '_id',
  as: 'subitems'
}}, {$unwind: {
  path: "$subitems",
  includeArrayIndex: 'string',
  preserveNullAndEmptyArrays: false
}}, {$match: {
  "subitems.number": 29
}}]

这可以正确地向我返回一个包含我要查找的子项目的文档。

现在,当我在猫鼬中尝试时:

let foundItems = await Item.aggregate([
    {
      '$lookup': {
        'from': 'subitems', 
        'localField': 'subitems', 
        'foreignField': '_id', 
        'as': 'subitems'
      }
    }, {
      '$unwind': {
        'path': '$subitems', 
        'includeArrayIndex': 'string', 
        'preserveNullAndEmptyArrays': false
      }
    }, {
      '$match': {
        'subitems.number': term,
        'status': {'$ne': 'deleted'}
      }
    }
  ]);

我总是没有文件。

我也尝试用基本的填充物来做到这一点:

Items.find({
    status: {"$ne": 'deleted'}
  })
  .populate({
    path: 'subitems',
    match: {
      number: term
    }
  });

但是,这将返回正确的项目,但包含所有子项目。

有什么我想念的吗?

1 个答案:

答案 0 :(得分:0)

找到答案,我将数字作为字符串传递给match函数,Mongo认为31"31"不相等。