是否可以在Mongodb中的两个数据库之间进行$ lookup聚合?

Ale*_*hel 13 mongodb mongodb-query mongodb-aggregation

我正在尝试做这样的事情:

use user; 

db.user.aggregate([
    {
      $lookup:
        {
          from: "organization.organization",
          localField: "organizationId",
          foreignField: "uuid",
          as: "user_org"
        }
   }
])
Run Code Online (Sandbox Code Playgroud)

user并且organization在两个不同的数据库中.

如果不可能,有哪些替代方案?

Cle*_*ath 13

是否可以在Mongodb中的两个数据库之间进行$ lookup聚合?

无法在两个不同的数据库中使用查询进行查询. mongodb支持中的$ lookup执行左外连接到同一数据库中的未整数集合.

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
Run Code Online (Sandbox Code Playgroud)

我们可以用来getSibling("dbname")从一个db查询另一个db

db.getSiblingDB('test').foo.find()
Run Code Online (Sandbox Code Playgroud)

参考 - MongoDB跨数据库查询

  • 不能在聚合中使用同级。 (2认同)

Gno*_*por 11

是的,只需阅读以下 mongodb 文档:

在 Atlas Data Lake 中,$lookup可用于执行来自不同数据库的集合的联接。

https://docs.mongodb.com/datalake/reference/pipeline/lookup-stage


loo*_*nis 6

对于那些不使用 Atlas Data Lake 的人来说,这是一个解决方法。

假设我们有collection1indb1collection2in db2

来自db1,首先合并collection2

db.getSiblingDB("db2").collection2.aggregate([
    {
        $match: { "key1": "optional some condition to limit the number of results" }
    },
    {
        $project: { k2: "$optional projection to limit object attributes" }
    },
    {
        $merge: { into: { db: "db1", coll: "tmpCollection2" } }

    }
])
Run Code Online (Sandbox Code Playgroud)

然后使用 is 来查找 collection1

db.collection1.aggregate([
    {
        $lookup: {
            from: "tmpCollection2",
            localField: "localField",
            foreignField: "k2",
            as: "tmpCollection2_docs"
        }
    },
    {
        //Simulate the inner join if needed
        $match: {
            "tmpCollection2_docs": {
                $ne: []
            }
        }
    },
    {
       // Transform the array if needed
        $addFields: {
            "tmpCollection2_docs": {
                $arrayElemAt: ["$tmpCollection2_docs", 0]
            }
        }
    }
])
Run Code Online (Sandbox Code Playgroud)