【问题标题】:how to filter documents from populate in mongoose如何从猫鼬中的填充中过滤文档
【发布时间】:2021-12-25 02:47:07
【问题描述】:

我有参考州和城市的预订模式。我只想从特定的一对城市、州获取文件(但只给出城市、州的名称)

const bookingSchema = new Schema({
    id: {
        type: String
    },
    service: {
        type: String
    },
    city: {
        type: Schema.Types.ObjectId,
        ref: 'City'
    }, 
    state: {
        type: Schema.Types.ObjectId,
        ref: 'State',
        
    }
})


const stateSchema=new Schema({
    name: {
        type: String
    }
})


const citySchema=new Schema({
    name: {
        type: String
    }
})

我需要来自bookingSchema 的包含 idservice 的输出(文档),但只有那些具有特定城市名称(例如例如name="New York")

在 SQL 中可以通过查询来完成:

SELECT * FROM bookings bk
   INNER JOIN city ct ON bk.city_id=ct.id
   INNER JOIN state st ON bk.state_id=st.id
   WHERE ct.name='city name' AND st.name='state name'

我也确实将populate 与匹配一起使用,但问题是它不会过滤 bookingSchema,但它实际上的工作方式是只填充具有给定状态名称的字段以及它提供的其他文档空。

请告诉我如何根据 REF 过滤文档

【问题讨论】:

  • 请提供城市和州的样本数据以及您喜欢的输出
  • const stateSchema=new Schema({ name: { type: String } }) const citySchema=new Schema({ name: { type: String } }) 我需要包含:id 和来自 bookingSchema 的服务,但只有那些具有城市名称=(例如“纽约”)的文档(可以多个)

标签: mongodb mongoose join mongodb-query mongoose-populate


【解决方案1】:

在这样的预订集合中使用聚合

  • lookup : 从城市集合中查找城市
  • lookup : 从状态集合中查找状态
  • 展开:破坏城市数组
  • 展开:破坏状态数组
  • 项目:创建最终结果

示例:https://mongoplayground.net/p/hGQFhkoujsC

db.booking.aggregate([
      {
        "$lookup": {
          "from": "city",
          "localField": "city",
          "foreignField": "_id",
          "as": "city"
        }
      },
      {
        "$lookup": {
          "from": "state",
          "localField": "state",
          "foreignField": "_id",
          "as": "state"
        }
      },
      {
        "$unwind": "$city"
      },
      {
        "$unwind": "$state"
      },
      {
        "$match": {
          "city.name": "New York",
          "state.name": "Test State"
        }
      },
      {
        "$project": {
          _id: 1,
          city: "$city.name",
          service: 1,
          state: "$state.name"
        }
      }
    ])

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 2021-10-07
    • 2022-12-10
    • 2019-07-17
    • 2020-05-14
    • 2021-04-26
    • 2013-10-05
    • 2016-08-17
    相关资源
    最近更新 更多