mongodb节点 - 按json对象数组查找文档

时间:2017-07-09 14:15:12

标签: node.js mongodb mongodb-query

我在nodejs项目中使用mongodb,其中我有一组用户:

{ "_id" : ObjectId("1"), "firstName": "John", "lastName" : "Doe", "age":20 }
{ "_id" : ObjectId("2"), "firstName": "Jane", "lastName" : "Doe", "age":22 }
{ "_id" : ObjectId("3"), "firstName": "Bob", "lastName" : "Smith","age": 32 }
{ "_id" : ObjectId("4"), "firstName": "John", "lastName" : "Smith","age":40}
{ "_id" : ObjectId("5"), "firstName": "John", "lastName" : "Deer","age":66}

我想要一个查询来返回一个文档ID数组,这些文档id匹配用户数组,按照我在这里给出的数组排序的名字和姓氏

这就是我想要摆弄的东西:

var usersToFind = [
  { firstName: "John", lastName: "Smith"},
  { firstName: "John", lastName:"Doe"}
];

db.collection('users').then(users => users.aggregate([
   { $match : { /* what to put here? */ } },
   { $addFields : { '__order' : { $indexOfArray : [usersToFind, /* Missing here something */} } },
   { $sort : { '__order' : 1 } }
]).toArray(results => {
  console.log(results);
  // Should print ["ObjectId(4)", "ObjectId(1)"];
});

由于我对mongodb的了解有限,我可能会遗漏一些关于如何使用mongodb的基本信息。

如果您能帮助我解决问题或向我展示更好的实现方法,我将不胜感激。

我总是可以迭代我的usersToFind数组并逐个查找文档,但我想在这里使用单个查询。另一种方法是使用$or$and

谢谢

2 个答案:

答案 0 :(得分:1)

使用带有投影的$or查询可以帮助您完成大部分工作:

db.collection('users').find({$or: usersToFind}).project({_id: 1}).toArray((err, docs) => {
  console.log(docs);
});

但排序是另一回事,因为MongoDB没有任何内置的自定义排序支持。有关处理该问题的一些方法,请参阅Permission Denied while trying to connect to Docker Daemon while running Jenkins pipeline in Macbook

答案 1 :(得分:0)

您可以使用find()。这是一个例子:

db.collection('users').find(
   {
     "firstName": "John",
     "lastName": "Doe"
   }
)

Here is the documentation

相关问题