Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

mongodb - Specify Multiple Criteria for Array Elements

I am reading the docs for mongodb here, I am not able to understand these two commands and the different between them.

db.users.find( { finished: { $elemMatch: { $gt: 15, $lt: 20 } } } )

My Understanding : At least one element needs to satisfy both the conditions together.

and

Combination of Elements Satisfies the Criteria ...one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both

db.users.find( { finished: { $gt: 15, $lt: 20 } } )

Question : How range matching on arrays happen? Is it like if one element satisfies $gt:15, this condition is used up and other elements are check for the rest conditions i.e. $lt:20?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

To understand what the documentation is saying you first need to understand how range query with array works.

Suppose you have the following document in your collection:

{ "finished" : [ 27, 3 ] },
{ "finished" : 17 }

The first query:

db.users.find( { "finished": { "$elemMatch": { "$gt": 15, "$lt": 20 } } } )

Will only return the document where "finished" is an array. This is because $elemMatch operator only matches documents where the field is an array and where a single element satisfy all the query criteria.

But the second query:

db.users.find( { "finished": { "$gt": 15, "$lt": 20 } } )

will return both documents which is probably not what you want as 27 is greater than 20 and 3 is less than 15. This is because 27 matches the first criteria and 3 the second. This behavior is what is mentioned in the documentation.

...one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both:

Conclusion:

Range queries against arrays will match as far as one or multiple elements in the array that match all the query criteria.

Lesson:

Don't use range query with arrays. You will get unexpected result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...