Query MongoDB with length criteria

后端 未结 4 517
南方客
南方客 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:07

    You can use MongoDB's $where query parameter to submit javascript to the server. E.g.,:

    db.myCollection.find( {$where: "(7 <= this.name.length) && (this.name.length <= 14)"} )
    

    http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

    0 讨论(0)
  • 2020-12-31 08:11

    $where queries are not very efficient. MongoDB

    If this is a frequently executed query, you might want to store the length in a separate field. Denormalization

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-31 08:19

    You can use a JavaScript expression.

    User.where("this.name.length >= 7 && this.name.length <= 14")
    
    0 讨论(0)
提交回复
热议问题