Find document with array that contains a specific value

前端 未结 10 1431
猫巷女王i
猫巷女王i 2020-11-22 04:06

If I have this schema...

person = {
    name : String,
    favoriteFoods : Array
}

... where the favoriteFoods array is popula

10条回答
  •  醉梦人生
    2020-11-22 04:17

    In case you need to find documents which contain NULL elements inside an array of sub-documents, I've found this query which works pretty well:

    db.collection.find({"keyWithArray":{$elemMatch:{"$in":[null], "$exists":true}}})
    

    This query is taken from this post: MongoDb query array with null values

    It was a great find and it works much better than my own initial and wrong version (which turned out to work fine only for arrays with one element):

    .find({
        'MyArrayOfSubDocuments': { $not: { $size: 0 } },
        'MyArrayOfSubDocuments._id': { $exists: false }
    })
    

提交回复
热议问题