javascript - 通过数组在 mongodb 中查找某个字段的文档?

标签 javascript mongodb mongoose

我正在尝试运行查询来查找包含电话号码数组的所有文档:

例如:

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”运算符:

$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/

使用您的示例,这应该适合您:

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

关于javascript - 通过数组在 mongodb 中查找某个字段的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24680798/

相关文章:

javascript - 在记录 Action 中变得空虚 - twilio

javascript - 在 Angular 2 应用程序中将一个属性传递给一个空的新对象

node.js - 如何处理 MongoDB 的断开连接错误

JavaScript 变量查询理解

javascript - Bootstrap 模式处于事件状态时无法捕获按键事件

javascript - 仍然对 jQuery 中的事件和事件处理程序感到困惑

javascript - 如何使用其他集合的子数组数据过滤来自mongo集合子数组的数据

node.js - Mongoose - 检查两个数字之间的值

node.js - Node JS mongodb : use global connection or local connection

javascript - 如何获得 Mongoose 属性(property)的总和?