skip to Main Content
{ field_name: { $not: { $lt: 100 } } }

How do I write the above using MongoDB aggregation language?

I cannot use:

{ $gte: ["$field_name", 100] }

because field_name may be missing. When it is missing, then it should always be true. This is the reason why I use $not.

The should be able to use indexes on field_name

2

Answers


  1. $not with $gt (not greater than) is equivalent to $lte (lesser or equal to).

    While you can use the $ifNull operator to define the default value if the field is null or missing.

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            $lte: [
              {
                $ifNull: [
                  "$field_name",
                  0
                ]
              },
              100
            ]
          }
        }
      }
    ])
    

    Demo @ Mongo Playground

    Login or Signup to reply.
  2. What is your problem? It should just work:

    db.collection.insertMany([
       { field_name: 50 },
       { field_name: 150 },
       { other_field: 0 },
       { field_name: null }
    ])
    
    db.collection.find({ field_name: { $not: { $lt: 100 } } })    
    [
      { _id: ObjectId("6459fc29927c6f7dd310d586"), field_name: 150 },
      { _id: ObjectId("6459fc29927c6f7dd310d587"), other_field: 0 },
      { _id: ObjectId("6459fc8e927c6f7dd310d588"), field_name: null }
    ]
    
    
    db.collection.aggregate([{ $match: { field_name: { $not: { $lt: 100 } } } }])
    [
      { _id: ObjectId("6459fc29927c6f7dd310d586"), field_name: 150 },
      { _id: ObjectId("6459fc29927c6f7dd310d587"), other_field: 0 },
      { _id: ObjectId("6459fc8e927c6f7dd310d588"), field_name: null }
    ]
    

    Index is used in either cases.

    $match documentation:

    The $match stage has the following prototype form:

    { $match: { <query> } }

    $match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search