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
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)?
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:
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.
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.
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/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/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:
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/spoink74 17d ago
If you’re in Atlas you can use stream processing to materialize a continuously updating view.