r/mongodb • • 17d ago

MongoDB

I’m trying to aggregate collections from two different database and getsiblingdb is not working. The alternate I found if mongo script but I couldn’t export the result. Whats the real time solution

1 Upvotes

5 comments sorted by

1

u/sereikis 17d ago

for a standard $lookup, the foreign collection must be in the same database; getSiblingDB() only selects a database for a shell operation, it doesn't change that limit. for a one-off export you can join the two query results in a client script and write JSON/CSV; which MongoDB version/deployment are you using, and what pipeline/error do you get (with sensitive data removed)?

1

u/sh4ruu 16d ago

1.35.0 is the version.
$lookup with syntax {from: {db:<>, Coll:<>,….} is not supported for db:<db_name> and Coll: <>. Is the error.

Somehow I figured it out with mongosh but I couldn’t export the data from the run

1

u/AxialDB 16d ago

getSiblingDB() is a shell helper, not a pipeline stage, so you can't use it inside aggregate(). $lookup and $unionWith only see collections in the same database. Options that work:

  1. Stage the data into one database: run a pipeline on db A that ends with { $merge: { into: { db: "B", coll: "a_copy" } } } (or $out with a db), then do your $lookup in B. Re-run it on a schedule or after writes.
  2. If you just need the result as a file, run the script non-interactively: mongosh "<uri>" --quiet --eval 'EJSON.stringify(db.getSiblingDB("A").coll.aggregate([...]).toArray())' > out.json. Or $out to a collection and mongoexport it as CSV/JSON.
  3. If this is recurring reporting across both databases, stop joining at query time and keep a read-only reporting copy that has both, so the join is cheap and production isn't doing the work.

Disclosure: we build AxialDB, which keeps MongoDB (and MySQL) collections as live SQL tables you can join across databases in one query: https://axialdb.com/

1

u/sh4ruu 16d ago

This helps!! Thank you

1

u/spoink74 17d ago

If you’re in Atlas you can use stream processing to materialize a continuously updating view.