Home > Enterprise >  Is there a mongoDB runCommand that returns multiple collections?
Is there a mongoDB runCommand that returns multiple collections?

Time:02-12

I'm trying to write a mongoDB runCommand that returns multiple collections with one command.

I have successfully used the find command within runCommand but I'm unsure how to return multiple find searches. It's important that they are not merged.

Something similar to:

db.runCommand(
   [{
      "find": "venues"
   },
   {
      "find": "guests"
   }]
)

Ideally the result would follow something similar to this structure:

{
  "venues": {all venue data from mongo},
  "guests": {all guest data from mongo}
}

CodePudding user response:

As I see, this question has nothing common with runCommand.RunCommand just runs a single command. What you really need is to use unionWith aggregate stage and possibly some post data processing.

db.orders.aggregate([
  {
    $unionWith: {
      coll: "inventory",
      pipeline: [
        {
          $addFields: {
            "fromInventory": 1  // add a flag that shows that this data is not from original collection
          }
        }
      ]
    }
  },
  {
    "$group": {
      "_id": "$fromInventory",
      "content": {
        "$addToSet": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      "content": 1, // also it's possible to exclude a flag from output via: `"content.fromInventory": 0,` instead `"content" : 1`
      _id: 0
    }
  }
])

See here. You may need to improve this result further for example with $replaceRoot

  • Related