如何使用ObjectId引用过滤查找聚合并在MongodDB中返回整个文档

时间:2019-06-25 09:38:31

标签: mongodb mongodb-query aggregation-framework

我正在开发票务系统,需要过滤具有给定属性的事件。

我的事件模型是这个。

const Event = new mongoose.Schema({
  name: String,
  slug: String,
  venue: {
    type: mongoose.Schema.Types.ObjectId,
    ref: venue.modelName,
  },
  promoters: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: promoter.modelName,
  }],
  artists: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: artist.modelName,
  }],
});

我的场地模型是这个

const Venue = new mongoose.Schema({
  name: String,
  slug: String,
  tags: [String],
  capacity: Number,
  promoters: [{
    type: mongoose.SchemaTypes.ObjectId,
    ref: promoter.modelName,
  }],
});

我写了一个查询查询

db.getCollection("events").aggregate([
// Lookup for venues
{ "$lookup": {
  "from": "venues",
  "localField": "venue",
  "foreignField": "_id",
  "as": "venue"
}},{"$unwind":"$venue"},

// Lookup for promoters.
{"$unwind":"$promoters"},
{ "$lookup": {
  "from": "promoters",
  "localField": "promoters",
  "foreignField": "_id",
  "as": "promoters"
}},

// Lookup for artists.
{"$unwind":"$promoters"},
{ "$lookup": {
  "from": "artists",
  "localField": "artists",
  "foreignField": "_id",
  "as": "artists"
}},
])

正确获取所有对象。

将艺术家查询查询更改为

// Lookup for artists.
{"$unwind":"$artists"},
{ "$lookup": {
  from: 'artists',
  as: 'artists',
  let: { artist: '$artist._id' },
  pipeline: [
    { $match: {
        $expr: { $eq: ['$slug', 'artist-1'] },
      }
    }
  ]
}},

MongoDB返回重复的结果,其中艺术家仅显示“ artist-1”。

我如何获取包含Artist-1的事件,并查看具有该事件的所有艺术家?

0 个答案:

没有答案