Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

casting - Is it possible to cast in a MongoDB-Query?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the following JavaScript expression:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...