Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cast in a MongoDB-Query?

Tags:

When I have two MongoDB documents like this...

db.test.insert( {"value" : "10123"} ); db.test.insert( {"value" : "160"} ); 

The result of a query like:

db.test.find({"value" :{$gt : "12"} }); 

is..

{ "_id" : ObjectId("4c6d1b92304326161b678b89"), "value" : "160" } 

It's obvious, that a string comparison is made, so that my first value is not returned. Is there any way to cast within the query?

Something like:

db.test.find({ (int) "value" :{$gt : 12} }); 

would be great. A query like

db.test.find({"value" :{$gt : 12} }); // without the quotes around "12" 

returns nothing.

like image 951
rgroli Avatar asked Aug 19 '10 12:08

rgroli


People also ask

What is projection query in MongoDB?

What are projection queries? In MongoDB, the default for queries is to return all fields in matching documents. A projection query is used to specify or restrict the data returned in query results. By specifying a projection query, you can specify the fields you want to return or exclude.

Can we perform joins in MongoDB?

Join Collections MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage. The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.

Can we run SQL query in MongoDB?

YES! A company called UnityJDBC makes a JDBC driver for mongodb. Unlike the mongo java driver, this JDBC driver allows you to run SQL queries against MongoDB and the driver is supported by any Java appliaction that uses JDBC.


2 Answers

You can use the following JavaScript expression:

db.test.find("this.value > 12") 

This uses JavaScript's automatic conversion from string to number.

like image 84
Niels van der Rest Avatar answered Dec 24 '22 21:12

Niels van der Rest


I have a similar workaround, i find that if you can use the mongo shell, you can write an statement to do this in javascript, but capable of using indexes.

var myItems = [] var it = db.test.find({},{value:1}) while (it.hasNext()){  var item = it.next();  if(parseInt(item.value) > 12)   myItems.push(item); } 

If you want this to run faster than previus solution, you have to ensure the index on the value field.

like image 30
Neoecos Avatar answered Dec 24 '22 20:12

Neoecos