【问题标题】:$lookup with two $concat fields带有两个 $concat 字段的 $lookup
【发布时间】:2019-05-02 11:08:41
【问题描述】:

鉴于这些文件:

{
    "name" : "User",
    "class" : "clazz",
    "reference" : "ref"
}

{
    "classReference" : "clazz+ref",
    "room" : "123"
}

如何进行 $lookup 来检索这样的文档(不更改文档):

{
    "name" : "User",
    "class" : "clazz",
    "reference" : "ref",
    "classReference" : "clazz+ref",
    "room" : "123"
}

【问题讨论】:

  • classReference 的值是多少? “clazz”还是“ref”?
  • 两者连接(符号选择不佳)。编辑问题以更好地反映我的愿望。
  • 那么文档中的referenced(common) 字段是什么?
  • 字段 classReference 是第一个文档的类和引用的串联。在 SQL 中,我会得到类似 SELECT * FROM user, room WHERE room.classReference = CONCAT(user.name, user.class)

标签: mongodb mongodb-query aggregation-framework mongodb-lookup


【解决方案1】:

您可以将以下聚合与 mongodb 3.6 及更高版本一起使用

db.user.aggregate([
  { "$lookup": {
    "from": Room.collection.name,
    "let": { "ref": { "$concat": ["$class", "$reference"] } },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$classReference", "$$ref"] } } }
    ],
    "as": "ref"
  }},
  { "$project": {
    "classReference": { "$arrayElemAt": ["$ref.classReference", 0] },
    "room": { "$arrayElemAt": ["$ref.room", 0] },
    "name": 1,
    "class": 1
    "reference": 1
  }}
])

基本上你需要$concatclassreference,然后将其传递给$lookup管道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2012-10-01
    • 2014-07-21
    • 2021-03-14
    • 2018-11-25
    相关资源
    最近更新 更多