0

In a MongoDb aggregation pipeline, I often encounter wanting to filter on an operation of a member field (i.e. size of a list). Is it possible doing this in one operation, rather than projecting a variable first, and then matching?

This is what I usually do:

[
  {
    "$project": {
      "vector_size": { "$size": "$VectorField" }
    }
  },
  {
    "$match": {
      "vector_size": { "$gte": 7 }
    }
  }
]

I would prefer a one-off, something like:

[
  {
    "$match": {
      "VectorField": { "$size": { "$gte": 7 } }
    }
  }
]

But for that operation $size expects an integer, and not another operation. It it possible?

casparjespersen
  • 3,460
  • 5
  • 38
  • 63
  • Try this `[{ "$match": { "$expr": { "$gte": [{ "$size": "$VectorField" }, 7] }} }]` – Ashh Oct 07 '18 at 10:46

1 Answers1

1

You can use find in one condition

db.getCollection('your-collection').find( {"$expr":{
   "$gte":[
     {"$size":'$VectorField'},
     7
   ]
 }})

Note: Tested in 3.6.5 on mongo GUI

IftekharDani
  • 3,619
  • 1
  • 16
  • 21