MongoDb query array with null values

后端 未结 3 1370
旧巷少年郎
旧巷少年郎 2021-02-20 07:51

I have objects in my collection that look like:

{ MyArray:[null, \"some value\", null] }

I want to query those objects that have a null value a

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-20 08:19

    In order to find documents with arrays, with null elements please run:

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

    According to safaribooksonline proper null matching is performed using $in (because you cannot use $eq with null). Also, comparing with null:

    {"something":null}
    

    will match documents with "something" field set to null and every document which does not have "something" field at all. Thus we have to make sure the key exists using $exists.

提交回复
热议问题