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



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

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

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

最新更新