Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

mongodb - Combining 2 collections after filtering 2nd one based on ids from first one

I have 2 collections like this:

Batches:

{
  "userId": "",
  "productId: "",
}

Products:

{
   "_id": "",
   "name": "",
}

What i want to do is filter the batches by userId first. And then get all products which i get ids in filtered elements of batches. I have seen a lot of examples but mostly goes the opposite way.

My final result i would like to look like this:

[{
   name: "product 1",
   batches: [...]
}]
question from:https://stackoverflow.com/questions/65642298/combining-2-collections-after-filtering-2nd-one-based-on-ids-from-first-one

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try lookup with aggregation pipeline,

  • $lookup in branches collection, pass productId in let, and match expression condition for for productId and filter userId
db.products.aggregate([
  {
    $lookup: {
      from: "branches",
      let: { productId: "$_id" },
      pipeline: [
        {
          $match: {
            userId: "1", // filter user id here
            $expr: { $eq: ["$$productId", "$productId"] }
          }
        }
      ],
      as: "brnaches"
    }
  }
])

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...