在mongodb中通过数组查找一个字段的文档

finding documents in mongodb by array for one field?

本文关键字:一个 字段 文档 mongodb 查找 数组      更新时间:2023-09-26

我试图运行一个查询来查找包含电话号码数组的所有文档:

例如:

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

一个示例文档将是:

{
  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
}

所以我试图运行一个查询来查找包含数组中任何这些元素的所有文档,我知道我可能可以运行一个for循环,但我宁愿尝试在一个查询中完成它。

我使用mongoose节点模块来查询我的结果。

例如:

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

您应该使用"$in"操作符:

在<<p> 美元/strong>

$in操作符选择字段值所在的文档等于指定数组中的任意值。

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

使用你的例子,这应该为你工作:

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