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,"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',"Product Division Id is required"] },name: { type: String,"Product Name is required"] },price: { type: Number,"Product Price is required"] },description: { type: String,"Product Description is required"] },technical_detail: { type: String,default: null },packing: { type: String,default: null }
});```

解决方法

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

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