MongoDB Match an array with $type?

后端 未结 2 2026
庸人自扰
庸人自扰 2020-12-03 21:18

I have a MongoDb collection contains of 284.116 tweets. The problem is the \"author\" field in some objects are in object type, but in other objects -this \"author\" field-

2条回答
  •  失恋的感觉
    2020-12-03 21:52

    Here's a better way to do what you originally asked; that is to actually check if a certain field holds an array type value:

    .find({ "author": { "$gte": [] } })
    

    MongoDB's $type functionality for arrays, though well documented, is IMO inconsistent with all the other $type checks, and obviously doesn't work for this use case, but since around 2.6, you can use the above query to check whether the value is an array (empty or not).

    I say this is "better" than the currently selected answer, because executing code via $where is not recommended, unless standard query constructs truly cannot get the job done.

    To elaborate, $where is not recommended due to performance via lack of ability to use indexes in executed code. More detail: https://docs.mongodb.com/manual/reference/operator/query/where/#considerations

    Also, if you'd like to check for non-empty arrays specifically, use this:

    .find({ "author": { "$gt": [] } })
    

    Technically, this one is also better than the current answer's corresponding $exists solution, as the field may have a non-array object with a field named "0", and that would match as a "non-empty array", which is wrong in that case.

提交回复
热议问题