Search code examples
mongodbmongoose

what is the proper way to use $nin operator with mongoDB


I want to find entries in my MongoDB collection that match some filters. Each entry in my mongo collection looks like this data:

{
    type: "admin"
    senderId: "6131e7c597f50700160703fe"
    read_by: [
        {
        Object_id: 614dbbf83ad51412f16c0757
        readerId: "60b968dc5150a20015d6fcae"
        }
    ]
},
{
    type: "admin"
    senderId: "6131e7c597f50700160703fe"
    read_by: [
        {}
    ]
}

What I want to achieve is to filter the collection to get only the entries that match 'admin' as the type and that don't have the current user's ID in the read_by array (that is an array of objects).

I wrote this (and tried some other combinations with errors), but it is not working. I get 0 entries on the end, but I expect to get one of the two as the second have it's read_by array empty.

Thank you very much!


Solution

  • I validated my solution using cloud.mongodb.com interface and the simplest following filter seems to do the job:

    { "read_by.readerId": {$ne:"60b968dc5150a20015d6fcae"}}
    

    Only the record with empty array is being returned.

    $nin operator works fine as well but if there is only single value for comparision then $ne should be enough.

    { "read_by.readerId": {$nin: ["60b968dc5150a20015d6fcae"]}}