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
159 views
in Technique[技术] by (71.8m points)

MongoDB : find value in Array with multiple criteria

I have the following documents:

{_id : 1, numbers : [-1000, 1000]}
{_id : 2, numbers : [5]}

I'm trying to get a query that will find a document that has a value in the numbers array that is between -10 and 10 (in this case, _id : 2). However, when I try the following:

db.foo.find({numbers : $and : [{$gt : -10},{$lt : 10}]})

it returns all documents. Is this possible to do without map-reduce? Thanks, -JWW

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

You can use $elemMatch to check if an element in an array matches a specified match expression.

In this case, you can use it to get a document whose numbers array has an element that is between -10 and 10:

   db.foo.find( { numbers : { $elemMatch : { $gt : -10 , $lt : 10 } } } );

This will just return the _id : 2 document.


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

...