skip to Main Content

I have a MongoDB document with number field:

[
  {
    _id: 1,
    number: 10
  },
  {
    _id: 2,
    number: 11
  },
  {
    _id: 3,
    number: 12
  }
]

And I’m using MongoDB filter $gte and $lte it looks like this:

db.collection.aggregate([{$match: {number: {$gte: 10, $lte: 100}}]

And I want to know is there the way to exclude some numbers? For example I have 100 documents with number from 10 to 100, and I do not want to get number 55 but I still need to use $gte and $lte. How can I do that?

And now I can split my gte and lte numbers and exclude 1 number, but what should I do if I need to exclude 2 or more numbers?

2

Answers


  1. As @cmgchess said in the comment section, you are able to exclude number with $ne and $nin.

    Database:

    [
      {
        "_id": 1,
        "number": 10
      },
      {
        "_id": 2,
        "number": 11
      },
      {
        "_id": 3,
        "number": 12
      },
      {
        "_id": 4,
        "number": 55
      },
      {
        "_id": 5,
        "number": 13
      },
      {
        "_id": 6,
        "number": 56
      },
      {
        "_id": 7,
        "number": 4
      },
      {
        "_id": 8,
        "number": 156
      }
    ]
    

    $ne query:

    db.collection.aggregate([
      {
        $match: {
          number: {
            $ne: 55,
            $gte: 10,
            $lte: 100
          }
        }
      }
    ])
    

    $nin query:

    db.collection.aggregate([
      {
        $match: {
          number: {
            $nin: [
              55,
              56
            ],
            $gte: 10,
            $lte: 100
          }
        }
      }
    ])
    
    Login or Signup to reply.
  2. db.collection.aggregate([
      {
        $match: {
          number: {
            $gte: 10,
            $lte: 100,
            $nin: [55, 65, 75] 
          }
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search