How do you query mongodb to find the length of a particular string/text field?
And how would you find the max length of a query set?
Probably the quickest and easiest way to check the size of a MongoDB collection is to use the db. collection. dataSize() method. This method returns the size of the collection in bytes.
MongoDB connector limits text field to 255 characters.
Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.
$expr can build query expressions that compare fields from the same document in a $match stage. If the $match stage is part of a $lookup stage, $expr can compare fields using let variables. See Perform Multiple Joins and a Correlated Subquery with $lookup for an example.
Starting Mongo 3.4
, the $strLenCP
aggregation operator can be used to get a string's length:
// { a: "Hello World" }
// { a: "42" }
// { a: "Hello World!" }
db.collection.aggregate([{ $addFields: { length: { $strLenCP: "$a" } } }])
// { a: "Hello World", length: 11 }
// { a: "42", length: 2 }
// { a: "Hello World!", length: 12 }
and in order to get the max length from all documents via a $group
/$max
stage:
db.collection.aggregate([
{ $group: { _id: null, longest: { $max: { $strLenCP: "$a" } } } }
])
// { "_id" : null, longest: 12 }
how about use regular expression instead.
> db.apps.find({$where:"(this.id.length gt 6) && (this.id.length lt 15) " } ).count(); 2548 > db.apps.find({$where:" (this.id.length gt 6) && (this.id.length lt 15) " } ).explain(); { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 2548, "nscannedObjects" : 88736, "nscanned" : 88736, "nscannedObjectsAllPlans" : 88736, "nscannedAllPlans" : 88736, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 1, "nChunkSkips" : 0, "millis" : 1523, "indexBounds" : { }, "server" : "shuhaimac.local:27017" }
> db.apps.find({id:/\w{7,16}/i}).count(); 2548 > db.apps.find({id:/\w{7,16}/i}).explain(); { "cursor" : "BtreeCursor id_1 multi", "isMultiKey" : false, "n" : 2548, "nscannedObjects" : 2548, "nscanned" : 88736, "nscannedObjectsAllPlans" : 2548, "nscannedAllPlans" : 88736, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 122, "indexBounds" : { "id" : [ [ "", { } ], [ /\w{7,16}/i, /\w{7,16}/i ] ] }, "server" : "shuhaimac.local:27017" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With