NeNaD
NeNaD

Reputation: 20304

MongoDB: Fetching documents from different collections in one query

I have two different collections for two different type of products. Now, I want to fetch all documents from both collections for a particular user.

I know I can do that with 2 queries for each collection, merging them on the server side and sending the result to the user. Downside of this is that I have to fetch all documents for a user from both collections, which is not good for pagination. That is why I want to do it in one query, so I can leave a pagination logic to MongoDB as well.

Here is the example of collections and expected result:

Products_type_1

[
  {
    "name": "product_1",
    "user": "user_1",
    ...
  },
  {
    "name": "product_2",
    "user": "user_2",
    ...
  }
]

Products_type_2

[
  {
    "name": "product_3",
    "user": "user_1",
    ...
  },
  {
    "name": "product_4",
    "user": "user_2",
    ...
  }
]

The expected result:

[
  {
    "type": "Products_type_1",
    "name": "product_1",
    "user": "user_1",
    ...
  },
  {
    "type": "Products_type_2",
    "name": "product_3",
    "user": "user_1",
    ...
  }
]

Upvotes: 0

Views: 50

Answers (2)

Alex Blex
Alex Blex

Reputation: 37038

You can use aggregation framework with $unionWith stage:

db.Products_type_1.aggregate([
  {
    "$match": {
      "user": "user_1"
    }
  },
  {
    $unionWith: {
      coll: "Products_type_2",
      pipeline: [
        {
          "$match": {
            "user": "user_1"
          }
        }
      ]
    }
  }
])

Playground: https://mongoplayground.net/p/v0dKCwiKsZU

If you want to use pagination you will need to add sort stage to ensure consistent order of the documents in the result.

Upvotes: 2

Neil Russell
Neil Russell

Reputation: 1

Firstly I would query the logic of having a different collection for the different 'product_type_x'. If you had a single collection with an added field...

{ "productType" : 1,
  ...
},

That way that issue has just been resolved, everything to do with Procts is now accessible in a single collection. Aggregation of your data now becomes simple (by comparison)

Upvotes: 0

Related Questions