简体   繁体   中英

MongoDB range search on numbers doesn't work as expected

I am trying to do a range search on some numbers in MongoDB.

I have the following two records. The import fields are the last two, value and type . I want to be able to get records back that have a value: withing some range.

{ "_id" : ObjectId("4eace8570364cc13b7cfa59b"), "sub_id" : -1630181078, "sub_uri" : "http://datetest.com/datetest", "pro_id" : -1630181078, "pro_uri" : "http://datetest.com/datetest", "type" : "number", "value" : "8969.0" }
{ "_id" : ObjectId("4eacef7303642d3d1adcbdaf"), "sub_id" : -1630181078, "sub_uri" : "http://datetest.com/datetest", "pro_id" : -1630181078, "pro_uri" : "http://datetest.com/datetest", "type" : "number", "value" : "3423.0" }

When I do this query

> db.triples.find({"value":{$gte: 908}});

So I do this query:

> db.triples.find({"value":{$gte: "908"}});

And again neither of the two expected records is returned, (although in this case some other record containing a date is returned).

I expect to get the two records above, but neither of them is displayed.

I can see that there are quotation marks around the numbers - does this mean they are being stored as "Strings" and therefore the numeric search doesn't work? I have very explicitly saved them as a Double hence the ".0" that's appearing.

Or could there be some other reason that the find(... query ...) command isn't working as expected?

EDIT:

Insertion code looks like this (exception handling removed):

t.getObject().getValue() returns a String - this is working fine. I then use this to instantiate a Double which is what I was hoping would get saved to MongoDB, and allow numeric range searches.

triple.put("value",new Double(t.getObject().getValue()));
DBCollection triples;
triples = db.getCollection("triples");
triples.update(triple,triple,true,false); 

You're right -- they are saved as strings and $gte will presumably use lexicographical order. Which mongoDB driver are you using? How exactly do you insert those records?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM