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

MongoDB $or query

I run following query in mongo shell:

db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )

It just returns nothing as expected(JSON)?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Use $in

For the query in the question, it's more appropriate to use $in

db.Profiles.find ( { "name" : { $in: ["gary", "rob"] } } );

Why doesn't it work

There's a missing quote - the cli is waiting for you to finish the second part of your or:

db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )
..............................................................^

You need to finish the query sufficiently for the cli to parse it for it to then say there's a syntax error.

Case insensitive matching

As indicated by a comment, if you want to search in a case insensitive manner, then you either use $or with a $regex:

db.Profiles.find ( { $or : [ { "name" : /^gary/i }, {"name": /^rob/i } ] } )

Or, you simply use one regex:

db.Profiles.find ( { "name" : /^(gary|rob)/i } )

However, a regex query that doesn't start with a fixed string cannot use an index (it cannot use an index and effectively do "start here until no match found then bail") and therefore is sub-optimal. If this is your requirement, it's a better idea to store a normalized name field (e.g. name_lc - lower case name) and query on that:

db.Profiles.find ( { "name_lc" : { $in: ["gary", "rob"] } } );

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

...