user1765862
user1765862

Reputation: 14145

Combining match filter in the aggregation

If I'm having an object Post with two properties

Scenario: total number of documents is 100. Those with IsHomePage set to true is 20 in total, the rest (80 in total documents) are documents with property IsTagged set to true.

how can I construct a query to select all 20 with IsHomePage and the random docs where IsTagged set to true with limit 50?

Upvotes: 0

Views: 315

Answers (1)

ray
ray

Reputation: 15217

You can use $unionWith to combine your 2 logic.

db.collection.aggregate([
  {
    "$match": {
      IsHomePage: true
    }
  },
  {
    "$unionWith": {
      "coll": "collection",
      "pipeline": [
        {
          "$match": {
            IsHomePage: {
              $ne: true
            },
            IsTagged: true
          }
        },
        {
          "$sample": {
            "size": 50
          }
        }
      ]
    }
  }
])

Here is the Mongo playground for your reference.

Upvotes: 1

Related Questions