简体   繁体   中英

finding documents in mongodb by array for one field?

Im trying to run a query to find all the documents that contain an array of phone numbers:

for example:

var mobileArray = ["07958485374","07958485375", "07958485378"];

an example document would be:

{
  phone_number: 07958483297,
  brand: "Mercedes",
  model: "S 350 L",
  year: 2007,
  price: 9500,
  description: "Full options - Automatic transmission - Gulf import - Excellent condition - V6 - Beig leather seats - Screen - Sunroof - CD - DVD - Telephone - Navigation - Xenon - Finger print - Bluetooth - Memory - Cruise control - Sensor - Wood - Clause examination - ",
  images_length: 4,
  _id: ObjectId("53a844d26d437e394844f0a3"),
  date: ISODate("2014-06-23T15:16:34.233Z"),
  __v: 0
}

So Im trying to run a query to find all documents that contains any of these elements in the array, I know I can probably run a for loop, but i would rather try do it in one query.

Im using mongoose node module to query my results.

for example:

 Car.find().where({"phone_number": "0795483297"}).limit(10).exec(function(err, docs) {
       res.send(docs);
  });

You should use the "$in" operator:

$in

The $in operator selects the documents where the value of a field equals any value in the specified array.

http://docs.mongodb.org/manual/reference/operator/query/in/

Using your example this should work for you:

Car.find({"phone_number": 
            { $in: ['0795483297', '07958485375', '07958485378']}
          }).limit(10).exec(function(err, docs) {
       res.send(docs);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM