[javascript] mongo vãi ò

Viewer

copydownloadembedprintName: mongo vãi ò
  1. // Define an array of company IDs you want to query
  2. var companyIds = [
  3.     ObjectId("company_id_1"),
  4.     ObjectId("company_id_2"),
  5.     // Add more company IDs as needed
  6. ];
  7.  
  8. // Query optimization
  9. db.company.aggregate([
  10.     // Match multiple companies
  11.     { $match: { _id: { $in: companyIds } } },
  12.     // Project only the necessary fields from the user collection
  13.     {
  14.         $project: {
  15.             name: 1,
  16.             users: {
  17.                 $filter: {
  18.                     input: "$users",
  19.                     as: "user",
  20.                     cond: { $in: ["$$user.company_id", companyIds] }
  21.                 }
  22.             }
  23.         }
  24.     },
  25.     // Unwind the users array
  26.     { $unwind: "$users" },
  27.     // Lookup orders belonging to the users
  28.     {
  29.         $lookup: {
  30.             from: "order",
  31.             let: { userId: "$users._id" },
  32.             pipeline: [
  33.                 { $match: { $expr: { $eq: ["$user_id", "$$userId"] } } },
  34.                 { $sort: { "created_at": -1 } }, // Sort orders by descending creation
  35.                 { $limit: 5 } // Limit the number of orders per user if needed
  36.             ],
  37.             as: "orders"
  38.         }
  39.     },
  40.     // Group by company and reconstruct the document
  41.     {
  42.         $group: {
  43.             _id: "$_id",
  44.             name: { $first: "$name" },
  45.             newest_orders: { $push: "$orders" }
  46.         }
  47.     }
  48. ]);
  49.  

Editor

You can edit this paste and save as new:


File Description
  • mongo vãi ò
  • Paste Code
  • 29 Mar-2024
  • 1.38 Kb
You can Share it: