Home > OS >  pymongo $lookup for two database. MongoDb Atlas
pymongo $lookup for two database. MongoDb Atlas

Time:11-14

It is pobbible to do a cross $lookup for different DB using pymongo? I found some solution in Atlas documentation, but it seems like it doen't work with pymongo, because from should be string (just a collection name). Can't find any other solutions that will work with pymongo

db.getSiblingDb("sourceDB1").orders.aggregate(
  {
    $lookup: {
      from: { db: "sourceDB2", coll: "catalog" },
      localField: "item",
      foreignField: "sku",
      as: "inventory_docs"
    }
  }
)

Thank everyone for helping.

Fould a lot of solution but it doen't work with pymongo

CodePudding user response:

Directly, the answer is "No, this is not possible at the time of writing via $lookup". The $lookup stage documentation mentions this directly several times (emphasis theirs):

Performs a left outer join to a collection in the same database to filter in documents from the "joined" collection for processing.

One possible solution would be to change the schema. This could include keeping the two collections in the same database, for example.

Now not to confuse things too much, but MongoDB also offers something called Data Federation in Atlas. This is notable because the $lookup implementation in that context (documented here) doesn't have the same restrictions (emphasis added):

In federated database instance, you can use $lookup to join sharded and unsharded collections from the same database or different databases from Atlas, AWS S3, and HTTP or HTTPS data stores.

There are important considerations here as it relates to ease of management and performance that should all be factored in as you decide on the approach that is most appropriate for your situation.

I don't believe any of this is specific to PyMongo.

  • Related