Untitled

 avatar
unknown
plain_text
a year ago
1.0 kB
17
Indexable
// Define an array of company IDs you want to query
var companyIds = [
    ObjectId("609b9fd5f0a31d06d44e8ab1"), // Company A
    ObjectId("609b9fd5f0a31d06d44e8ab2")  // Company B
];

// Aggregation pipeline
var aggregationPipeline = [
    {
        $match: { _id:{$in: companyIds}}
    },
    {
        $lookup:{
            from: "users",
            localField:"_id",
            foreignField:"company_id",
            as: "companyUser"
        }
    },
    {
        $unwind: "$companyUser"
    },{
        $lookup:{
            from: "orders",
            localField:"companyUser._id",
            foreignField:"user_id",
            as: "userOrder"
        }
    },
    {
        $unwind: "$userOrder"
    },
    {
        $sort:{createdAt: -1}
    },
    {
        $group: {
            _id: "$_id",
            name: { $first: "$name" },
            newest_orders: { $push: "$userOrder" }
        }
    }
];

// Run the aggregation query
db.companies.aggregate(aggregationPipeline).explain('executionStats');
Editor is loading...
Leave a Comment