[英]How to pass results from one query to another in Robo3T
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.我试图将一个 MongoDB 查询的结果传递给另一个,但结果在 Object 中,我需要它作为一个数组。 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.问题是我无法将其封装在外部 function 中,因为我无法通过 function 参数传递此“_id”。 Any ideas on how to automate it?
关于如何自动化它的任何想法?
You can use aggregate() to combine all ids in a array,您可以使用aggregate()组合数组中的所有 id,
country
condition country
条件null
means none and push _id
in array ids
null
表示无并在数组ids
中推送_id
_ids
and hide _id
_ids
并隐藏_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游乐场: 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 $match
country
条件products
collection using localField _id
to foreignField locId
_id
加入products
集合到 foreignField locId
products
array products
数组$group
by _id
null and push all products in products
$group
by _id
null 并推送产品中的所有products
$unwind
to deconstruct products
array $unwind
解构products
数组$project
to show required fields $project
显示必填字段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游乐场: https://mongoplayground.net/p/xOnohm0OWBV
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.