2

I'm trying to pass the results from one MongoDB query to another but the results are in Object and I need it as an Array. Example:

var locId = db.getCollection('locations').find({country:"France"}, {_id:1}).toArray()

How can I pass the results to another query:

db.getCollection('products').find({locId: {$in: locId }})

The results from the first query are something like:

array[1] [
obj[0] {_id: LocId123},
obj[1] {_id: LocId456},
obj[1] {_id: LocId789},
]

I was able to pass the values with this:

locId = Array.from(locId , value => value._id )

The problem is that I cannot encapsulate this in an external function because I cannot pass this "_id" by the function parameters. Any ideas on how to automate it?

Ivo Hristov
  • 83
  • 1
  • 5

1 Answers1

2

You can use aggregate() to combine all ids in a array,

  • $match country condition
  • $group by null means none and push _id in array ids
  • $project to show _ids and hide _id
var locId = db.getCollection('locations').aggregate([
  { $match: { country: "france" } },
  {
    $group: {
      _id: null,
      ids: { $push: "$_id" }
    }
  },
  {
    $project: { _id: 0, ids: 1 }
  }
])

Playground: https://mongoplayground.net/p/8_uzjCNMy00

Result:

[{
    "ids": [1, 2, 3]
}]

You Can Access:

db.getCollection('products').find({locId: {$in: locId[0]['ids'] }})


If you want to combine both query in single aggregation query then try,

  • $match country condition
  • $lookup to join products collection using localField _id to foreignField locId
  • $unwind to deconstruct products array
  • $group by _id null and push all products in products
  • $unwind to deconstruct products array
  • $project to show required fields
var products = db.getCollection('locations').aggregate([
  {
    $match: { country: "france" }
  },
  {
    $lookup: {
      from: "products",
      as: "products",
      localField: "_id",
      foreignField: "locId"
    }
  },
  { $unwind: "$products" },
  {
    $group: {
      _id: null,
      products: { $push: "$products" }
    }
  },
  { $unwind: "$products" },
  {
    $project: {
      _id: "$products._id",
      locId: "$products.locId"
    }
  }
])

Playground: https://mongoplayground.net/p/xOnohm0OWBV

turivishal
  • 34,368
  • 7
  • 36
  • 59