最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何通过mongodb中的引用字段查询?

运维笔记admin9浏览0评论

如何通过mongodb中的引用字段查询?

如何通过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" }}
])
发布评论

评论列表(0)

  1. 暂无评论