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?
You can use aggregate() to combine all ids in a array,
country conditionnull means none and push _id in array ids_ids and hide _idvar 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 conditionproducts collection using localField _id to foreignField locIdproducts array$group by _id null and push all products in products$unwind to deconstruct products array$project to show required fieldsvar 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With