【问题标题】:Writing a MongoDB query to filter based on a reference's attributes?编写 MongoDB 查询以根据引用的属性进行过滤?
【发布时间】:2019-03-11 04:37:21
【问题描述】:

假设我有一组称为“狗”的文档,一组称为“所有者”的文档,以及每个狗文档中对所有者的引用。

例如:

dog1:
{"_id": "abcdef0123456789",
 "name": "Rover",
 "owner": ObjectId("1234567890abcdef")}

owner1:
{"_id": "1234567890abcdef",
 "name": "Bob"}

那么,在这个例子中,我如何找到主人名为“Bob”的所有狗。

这是一个现有的数据库,所以我无法更改它存储数据的方式。我被当前的格式卡住了。

【问题讨论】:

  • 您是否将 _id 作为字符串存储在集合所有者中?
  • @thev0id 是 Mongo 创建对象时分配的 ID。所以,不是吗?

标签: python python-3.x mongodb aggregation-framework pymongo


【解决方案1】:

你可以在mongodb 3.6及以上尝试$lookup聚合以下

db.owner.aggregate([
  { "$match": { "name": "Bob" }},
  { "$lookup": {
    "from": "dogs",
    "let": { "ownerId": "$_id" },
    "pipeline": [{ "$match": { "$expr": { "$eq": ["$owner", "$$ownerId"] }}}],
    "as": "dogs"
  }}
])

或使用 3.4 $lookup 及更高版本

db.owner.aggregate([
  { "$match": { "name": "Bob" }},
  { "$lookup": {
    "from": "dogs",
    "localField": "_id",
    "foreignField": "owner",
    "as": "dogs"
  }}
])

【讨论】:

  • 3.4 版本是否仍然适用于 3.6?因为这看起来容易多了。
  • 抱歉没听明白?
猜你喜欢
  • 2012-11-12
  • 1970-01-01
  • 2022-11-19
  • 2014-12-15
  • 1970-01-01
  • 2020-03-24
  • 2015-02-26
  • 2020-10-07
  • 2019-07-12
相关资源
最近更新 更多