如何通过mongodb中的引用字段查询?
我有2个mongo架构:
用户:
{
_id: ObjectId,
name: String,
country: ObjectId // Reference to schema Country
}
国家:
{
_id: ObjectId,
name: String
}
我想让所有用户都有国名是越南。
我可以使用什么查询(只对用户查询)?
我想看起来像这样的SQL查询:
SELECT *
FROM User
JOIN Country
ON User.country = Country._id
WHERE Country.name = VietNam
回答如下:
您可以使用mongodb 3.6及更高版本的以下聚合
db.country.aggregate([
{ "$match": { "name": "VietNam" } },
{ "$lookup": {
"from": Users.collection.name,
"let": { "countryId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$country", "$$countryId" ] } } },
],
"as": "users",
}},
{ "$unwind": "$users" },
{ "$replaceRoot": { "newRoot": "$users" }}
])