Home > Mobile >  complex query without unionWith available
complex query without unionWith available

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

When using mongodb aggregation framework and $unionWith I can select in one DB round trip what I need (all docs where IsHomePage set to true and the rest for as many as it is with the property IsTagged set to true.

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

How can I achieve the same for older MongoDB instance (where there is an older version than 4.4).

Note: UnionWith is announced in version 4.4.

CodePudding user response:

Query

  • this can do what union does, but with the limitations of facet (each result array <16 MB the second is for sure because $sample)

*if its not what you want, if you can give sample data, and expected results to write query test it.

Test code here

aggregate(
[{"$facet": 
    {"home": [{"$match": {"$expr": {"$eq": ["$IsHomePage", true]}}}],
      "notHome": 
      [{"$match": 
          {"$expr": 
            {"$and": 
              [{"$ne": ["$IsHomePage", true]}, {"$eq": ["$IsTagged", true]}]}}},
        {"$sample": {"size": 50}}]}},
  {"$project": {"union": {"$concatArrays": ["$home", "$notHome"]}}},
  {"$unwind": {"path": "$union"}},
  {"$replaceRoot": {"newRoot": "$union"}}])
  • Related