mongodb从数组中查找,然后通过引用从对象ID中查找

时间:2021-07-16 06:41:32

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

我想用产品部门 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 }
});```

1 个答案:

答案 0 :(得分:0)

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

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