Home > Mobile >  Combining match filter in the aggregation
Combining match filter in the aggregation

Time:10-15

If I'm having an object Post with two properties

  • Title of type string
  • IsHomePage of type boolean
  • IsTagged of type boolean

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?

CodePudding user response:

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.

  • Related