0

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> 
1
  • 1
    Are you sure you want to query by a particular array index? Thats going to be very fragile code. Commented Dec 10, 2015 at 16:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.