在mongodb的另一个查询中使用上一个查询的结果 [英] Use result from previous query in another query in mongodb
本文介绍了在mongodb的另一个查询中使用上一个查询的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一个查询:
db.a.find({
"type": ObjectId("50ed90f5a70defef23000002"),
"config.name": "alpha"
}, {
"user": 1
})
第一个查询结果:
{ "_id" : ObjectId("5684035c91b4693b39547591"), "user" : ObjectId("54ba80ac2735eea200623612") }
第二个查询:
db.users.find({
"_id": ObjectId("54ba80ac2735eea200623612")
}, {
"lastname": 1
})
我可以将这两个查询合并为一个查询吗?第二查询使用第一查询结果的"user"
值ObjectId("54ba80ac2735eea200623612")
can I combine these two queries into one query? 2st query uses 1st query result's "user"
value ObjectId("54ba80ac2735eea200623612")
推荐答案
您可以使用带有$match
的聚合来匹配您的条件,并且可以使用$lookup
将本地字段user
映射到您的user
集合_id
字段:
You can use an aggregation with a $match
to match your condition and $lookup
to map your local field user
to your user
collection _id
field :
db.a.aggregate(
[{
$match: {
"type": ObjectId("50ed90f5a70defef23000002"),
"config.name": "alpha"
}
}, {
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "users"
}
}, {
$unwind: "$users"
}]);
例如,在Javascript中,可以使用mongoose
来完成此操作:
In Javascript, with mongoose
for example you can do this with :
YourModel.aggregate(
[{
$match: {
"type": ObjectId("50ed90f5a70defef23000002"),
"config.name": "alpha"
}
}, {
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "users"
}
}, {
$unwind: "$users"
}],
function(err, result) {
console.log("lastname : " + result.users.lastname);
});
这篇关于在mongodb的另一个查询中使用上一个查询的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文