【问题标题】:filter by subdocument while showing all parent document mongoose mongodb在显示所有父文档时按子文档过滤 mongoose mongodb
【发布时间】:2020-12-29 14:31:29
【问题描述】:

这是模式模型

const tokoSchema = new mongoose.Schema({
    name: String
    product: [{display: Boolean}]
}

所以,我想要的是通过product.display 过滤数据。当我使用toko.find({"product.display": true}) 过滤它时,它只显示具有product.display: true 的toko 列表,但我想要的是如果产品显示为假,它会继续显示toko 的_idname,产品数组为空@987654327 @。预期查询示例

// showing all tokos
[
  {
   _id: blabla
   name: "test",
   product: [{_id: blabla, display: true}], // filter display:true
   },
   {
   _id: blabla,
   name: "test",
   product: [] // no product with display:true
   }
 ]

toko.find({"product.display": true}) 查询示例

// not showing all tokos
[
  {
   _id: blabla
   name: "test",
   product: [{_id: blabla, display: true}]
   },
 ]

有什么解决办法吗?我应该使用聚合吗?

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您需要$filter 来获取数组:

    db.toko.aggregate([
        {
            $addFields: {
                product: {
                    $filter: {
                        input: "$product",
                        cond: {
                            $eq: [ "$$this.display", true ]
                        }
                    }
                }
            }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2018-01-26
      • 2019-07-13
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多