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

mongodb queries both with AND and OR

can I use combination of OR and AND in mongodb queries?

the code below doesn't work as expected

db.things.find({
           $and:[
                {$or:[
                     {"first_name" : "john"}, 
                     {"last_name" : "john"}
                ]},
                {"phone": "12345678"}
            ]});

database content:

> db.things.find();
{ "_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" }
{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }

when querying the above query - i get nothing!

> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});
>

I'm using mongo 1.8.3

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
 db.things.find( {
      $and : [
               { 
                 $or : [ 
                         {"first_name" : "john"},
                         {"last_name" : "john"}
                       ]
               },
               { 
                 "Phone":"12345678"
               }
             ]
    } )

AND takes an array of 2 expressions OR , phone.
OR takes an array of 2 expressions first_name , last_name.

AND

  • OR

    • first_name
    • last_name
  • Phone Number.

Note: Upgrade to latest version of MongoDB, if this doesn't work.


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

...