Find documents with arrays not containing a document with a particular field value in MongoDB

前端 未结 2 1303
一个人的身影
一个人的身影 2020-12-05 03:56

I\'m trying to find all documents that do not contain at least one document with a specific field value. For example here is a sample collection:

{  _id : 1         


        
相关标签:
2条回答
  • 2020-12-05 04:13

    Use the $ne operator:

    db.collection.find({'docs.foo': {$ne: 1}})
    

    Update: I'd advise against using $nin in this case.

    {'docs.foo': {$ne: 1}} takes all elements of docs, and for each of them it checks whether the foo field equals 1 or not. If it finds a match, it discards the document from the result list.

    {'docs.foo': {$nin: [1]}} takes all elements of docs, and for each element it checks whether its foo field matches any of the members of the array [1]. This is a Cartesian product, you compare an array to another array, each element to each element. Although MongoDB might be smart and optimize this query, I assume you only use $nin because "it has do to something with arrays". But if you understand what you do here, you'll realize $nin is superfluous, and has possibly subpar performance.

    0 讨论(0)
  • 2020-12-05 04:27

    Using $nin will work, but you have the syntax wrong. It should be:

    db.collection.find({'docs.foo': {$nin: [1]}})
    
    0 讨论(0)
提交回复
热议问题