[javascript] mongo vãi ò
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- // Define an array of company IDs you want to query
- var companyIds = [
- ObjectId("company_id_1"),
- ObjectId("company_id_2"),
- // Add more company IDs as needed
- ];
- // Query optimization
- db.company.aggregate([
- // Match multiple companies
- { $match: { _id: { $in: companyIds } } },
- // Project only the necessary fields from the user collection
- {
- $project: {
- name: 1,
- users: {
- $filter: {
- input: "$users",
- as: "user",
- cond: { $in: ["$$user.company_id", companyIds] }
- }
- }
- }
- },
- // Unwind the users array
- { $unwind: "$users" },
- // Lookup orders belonging to the users
- {
- $lookup: {
- from: "order",
- let: { userId: "$users._id" },
- pipeline: [
- { $match: { $expr: { $eq: ["$user_id", "$$userId"] } } },
- { $sort: { "created_at": -1 } }, // Sort orders by descending creation
- { $limit: 5 } // Limit the number of orders per user if needed
- ],
- as: "orders"
- }
- },
- // Group by company and reconstruct the document
- {
- $group: {
- _id: "$_id",
- name: { $first: "$name" },
- newest_orders: { $push: "$orders" }
- }
- }
- ]);
Editor
You can edit this paste and save as new: