MongoDB中如何通过引用字段进行查询?

Vũ *_*ũng 4 javascript mongoose mongodb node.js aggregation-framework

我有两个 Mongo 模式:

用户:

{
  _id: ObjectId,
  name: String,
  country: ObjectId // Reference to schema Country
}
Run Code Online (Sandbox Code Playgroud)

国家:

{
  _id: ObjectId,
  name: String
}
Run Code Online (Sandbox Code Playgroud)

我想获取所有国家/地区名称为“VietNam”的用户。

对于这种情况,我可以使用哪种查询(仅针对用户模式)?

我希望它看起来像这样的 SQL 查询:

SELECT * 
FROM User
JOIN Country 
ON User.country = Country._id 
WHERE Country.name = 'VietNam'
Run Code Online (Sandbox Code Playgroud)

Ash*_*shh 6

您可以在 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" }}
])
Run Code Online (Sandbox Code Playgroud)