0

I have 2 databases. Suppose first DB is X and second DB is Y. X has its own admin DB and Y has its own admin DB. Both X and Y are hosted on the same server.

I want to pull out data from both the DB's X and Y and use it in a query. Is it possible to do that?

3
  • IF those DB's are in same instance, they can't have different admin DB. Only if you run two different instances of mongodb (different ports) you can have different DBs with different admin DBs.
    – JJussi
    Oct 12 at 7:02
  • What do you mean by "database"? See docs.mongodb.com/manual/core/databases-and-collections Oct 14 at 10:05
  • @gunjan What's your requirement? You want to just fetch data from DBs X,Y within a single connection or you want to a single query to join both data from DBs X,Y?
    – Jerry
    Oct 17 at 11:13
0

You cannot use the data directly in an aggregation pipeline, but you can read the data from other databases and use variables. For example

var remoteDB = Mongo("mongodb://username:password@localhost:27016/admin?authSource=admin").getDB("test")
var docs = remoteDB.collection.find().toArray();

db.collection.aggregate([
   {
      $set: {
         remoteData: {
            $filter: {
               input: docs,
               as: "remote",
               cond: { $eq: ["$_id", "$$remote._id"] }
            }
         }
      }
   }
])

would be equivalent to this (pseudo-) $lookup:

db.collection.aggregate([
   {
      $lookup: {
         from: "test.collection@remoteDB",
         localField: "_id",
         foreignField: "_id",
         as: "remoteData"
      }
   }
])

A copy could be done like this:

var remoteDB = Mongo("mongodb://username:password@localhost:27016/admin?authSource=admin").getDB("test")
var docs = remoteDB.collection.find().toArray();

db.dummy_collection.insertOne({})    
db.dummy_collection.aggregate([
   { $limit: 1 },
   { $project: { data: docs } },
   { $unwind: "$data" },
   { $replaceRoot: { newRoot: "$data" } },
   { $out: "copied_collection" }
])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.