【问题标题】:mongodb find from array and then from object id by refrencemongodb 从数组中查找,然后通过引用从对象 id 中查找
【发布时间】:2021-09-24 23:53:12
【问题描述】:

我想搜索带有产品部门 ID 的订单列表。意味着我可以提供部门 ID 并获取该特定部门的订单列表。

我正在尝试这个查询,但它返回 0 个元素

db.getCollection('orders').find({$or:
[{'orderlist':{"$elemMatch":{'product_id.division_id':ObjectId("5f5b1511a859865ac9b0efe5")}}}]
})

我的订单架构



const orderSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    orderlist: [{
        product_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: [true, "Product Id is Required"] },
        quantity: { type: Number, required: [true, "Product Quantity is Required"] },
        packing_type: { type: String, default: null }
    }]
});

我的产品架构

const productSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    division_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Division', required: [true, "Product Division Id is Required"] },
    name: { type: String, required: [true, "Product Name is Required"] },
    price: { type: Number, required: [true, "Product Price is Required"] },
    description: { type: String, required: [true, "Product Description is Required"] },
    technical_detail: { type: String, default: null },
    packing: { type: String, default: null },
    packing_type: { type: String, default: null }
});```

【问题讨论】:

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


    【解决方案1】:

    要过滤带有 ref 架构的查询调用,首先您需要从服务器中查找它。在您的情况下,它是一个猫鼬对象 id 而不是元素的对象。 要合并模式,我建议使用聚合。$lookup(aggregation)

    db.getCollection('orders').aggregate([
    {
      $lookup: {
        from: 'product',
        localField: 'orderlist.product_id',
        foreignField: '_id',
        as: 'products',
      },
    },
    ])
    

    【讨论】:

    • 感谢您的回复,但我想通过division_id获取订单列表,division_id在产品型号中。大致意思是我可以说是:orderlist 是存在产品 id 的数组,我必须通过 product_id.division_id 查找;
    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多