Search code examples
mongodbpymongokeyword-search

Find all documents not having a keyword in array mongodb


Consider these 3 documents.

{
    '_id': ObjectId('5b9035e7b93fee6022c31201'),
    'keyword': ['a', 'b']
}, 

{
    '_id': ObjectId('5b9035e7b93fee6022c31202'),
    'keyword': ['a']
}, 

{
    '_id': ObjectId('5b9035e7b93fee6022c31203'),
    'keyword': ['b', 'c']
}

I want to match the documents where keyword a is not present.

So, the result should be:

{
    '_id': ObjectId('5b9035e7b93fee6022c31203'),
    'keyword': ['b', 'c']
}

How to do this in mongodb?


Solution

  • You can use $nin query operator

    db.collection.find({ "keyword": { "$nin": ["a"] }})
    

    or either $ne query operator

    db.collection.find({ "keyword": { "$ne": "a" }})