如何将MongoDB数组集合中的值与ID数组匹配?

时间:2018-12-21 10:59:40

标签: node.js mongodb mongoose mongodb-query

我在数组中有ID列表

Employees array

let employeeIds= [
    ObjectId("5b0d4c5ec47e6223a08af5fd"),
    ObjectId("5b1625f762368179e1e4549c"),
    ObjectId("5b3a15979a68763230202dfd"),
    ObjectId("5b3b0ea9074f944699f1bcfc"),
    ObjectId("5b45eb1214e42414cc9a2191"),
    ObjectId("5b83e3fc6fcad70850159ae2"),
    ObjectId("5bdc5a8ab8d82616a54b5667"),
    ObjectId("5bdc5b43d9c22617406f5b4d"),
    ObjectId("5bdd3a9da9ad6b138b503d7d"),
    ObjectId("5bf7e3840c414b4a1612da36"),
    ObjectId("5c18d04256573a536a201599"),
    ObjectId("5c18d05b56573a536a2015a2"),
    ObjectId("5ba8c52a5e0e986f16102c6f"),
    ObjectId("5ba34247decd71414691021d"),
    ObjectId("5bdd3d0ccf9d1417166e47ec")
]

在我的mongodb存储集合中,有数组中的员工列表

{
     "_id" : ObjectId("5b0d3fa6b426ea12ec0f6e5a"),
    "name" : "xxxx",
    "email" : "xxx@yyy.com",
    "telephone" : "24301212",
    "mobile" : "+91********",
    "employees" : [ 
        ObjectId("5b0d4c5ec47e6223a08af5fd"), 
        ObjectId("5b45eb1214e42414cc9a2191"), 
        ObjectId("5b3b0ea9074f944699f1bcfc"), 
        ObjectId("5b1625f762368179e1e4549c"), 
        ObjectId("5b83e3fc6fcad70850159ae2"), 
        ObjectId("5bdc5a8ab8d82616a54b5667"), 
        ObjectId("5bdc5b43d9c22617406f5b4d"), 
        ObjectId("5bdd3a9da9ad6b138b503d7d"), 
        ObjectId("5b3a15979a68763230202dfd"), 
        ObjectId("5bf7e3840c414b4a1612da36"), 
        ObjectId("5c18d04256573a536a201599"), 
        ObjectId("5c18d05b56573a536a2015a2")
    ],
}

我需要使用mongodb查询将商店员工集合中的employee数组进行比较。我尝试使用find()商店并使用lodash吸引了所有与此商店集合中匹配的员工。我该如何处理?你能提出任何想法吗?

1 个答案:

答案 0 :(得分:0)

这将返回所有至少雇用一名员工的商店。

store.find({
 employees :  {
  $elemMatch: 
   { 
    $in : [ ObjectId("5ba8c52a5e0e986f16102c6f"), ObjectId("5ba34247decd71414691021d")]
   }
 }
})