irom
irom

Reputation: 3596

mongodb array string element query

I am querying array of strings in mongdb and it does not work with $gt/$lt operators, see below. "cpu" array 3rd element is string "12"

nms:PRIMARY> db.checkpoints.find({ "cpu.3": "12" }).limit(1)
{ "_id" : ObjectId("5665ed5d601be0ed56d4ca0a"), "day" : "1", "hostname" : "WAL-VSX-02", "time" : "15:33:54", "con" : [ "75", "44", "10", "25997", "8895", "13788", "338", "20", "226" ], "cpu" : [ "0", "0", "0", "12", "0", "2", "0", "0", "0" ], "__v" : 0 }
nms:PRIMARY> db.checkpoints.find({ "cpu.3": {$gte: 10}})
nms:PRIMARY> 

Upvotes: 0

Views: 288

Answers (2)

Sede
Sede

Reputation: 61225

The only reason you are not getting any output is because "cpu" is an array of string. You will need to use the $where operator which does a JavaScript evaluation and cannot take advantage of indexes as mentioned in the documentation.

db.checkpoints.find({ "$where": function() {
    return parseFloat(this.cpu[3]) >= 10;
}})

I'll suggest you change your document structure and convert "cpu" elements to float.

Upvotes: 1

You are storing the values of the cpu array as strings, but you are comparing against an integer. If you change the array to int values your query will work.

Upvotes: 1

Related Questions