Query MongoDB with length criteria

后端 未结 4 536
南方客
南方客 2020-12-31 07:40

I have several documents in a MongoDB Collection, with a field \'name\' (which is a String).

How can I perform queries like 7 <= name.length <= 14

4条回答
  •  耶瑟儿~
    2020-12-31 08:16

    Mongo provides a few ways to perform a query with length criteria – $where or $regex are two great options however I would recommend using $regex due to better query performance.


    $where (slower)

    Accepts either a JavaScript expression or function in queries

    Example:

    db.collection.find({ $where: 'this.name.length >= 7 && this.name.length <= 14' })
    

    Note: The $where operator will not take advantage of your database indexes, resulting in a much slower query. - Source


    $regex (faster)

    Provides regular expression capabilities for pattern matching strings in queries

    Example:

    db.collection.find({ name: { $regex: /^.{7,14}$/ } })
    

    Note: The $regex operator will take advantage of your database indexes, resulting in a much faster query (if your collection is indexed properly). - Source

提交回复
热议问题