Is it possible to combine unrelated collection and then perform task?

Please bare with me for I just started working with mongoDB. Here’s my sample scenario. I have 3 collections: Dogs, Cats and PetsInventory and a pet data that I need to insert in PetsInventory collection.

Dogs Collection:

{
  "total": 3,
  "breeds": [
      { "_id": d1, "name": "labrador" },
      { "_id": d2, "name": "dalmatian" },
      { "_id": d3, "name": "husky"}
   ]
}

Cats Collection:

{
  "total": 3,
  "breeds": [
      { "_id": c1, "name": "persian" },
      { "_id": c2, "name": "ragdoll" },
      { "_id": c3, "name": "siamese" }
   ]
}

PetsInventory Collection:

{
   "total": 0,
   "items": []
}

And a pet data to be inserted in PetsInventory Collection:

{
   "_id": p1
   "petOriginId" : c1
   "description": "male labrador"
}

I need to save the pet data to PetsInventory collection but before that, i need to find out if the value of its petOriginId field is existing in either Dogs collection or Cats collection otherwise it wont be inserted. Thank you in advance!

Your best bet is to manually check if the records are present according to your specifications, and if they are indeed present - you can go ahead and insert them.

So step 1 is to check manually if the documents are present according to your specifications:

db.getCollection('Dogs').findOne({"breeds._id": c1},{"breeds.$":1}) where ‘c1’ is the value of the ‘petOriginId’ to be inserted into the PetsInventory Collection. If the value returned is null, then perform the second search on ‘Cats’ collection. If result is null then exit else do something like this:

db.getCollection('PetsInventory').updateOne({_id: p1},{$push:{items: document_to_be_pushed},$inc:{total:1}})

Since these are values you are checking against, and not collections at large, I don’t think aggregations can be used. But you can try using mapReduce() to get what you want to achieve in a single call to database.

1 Like