猫鼬$ elem与多个相同属性匹配

时间:2019-01-30 17:25:46

标签: arrays node.js mongodb mongoose

我正尝试通过以下查询与猫鼬一起find()

let users = await models.users.find({
  inv: { $elemMatch: { name: "Some Item", name: "Another Item" } }
});

应该找到这些文件:

{
  inv: [{ name: "Some Item", amount: 5 }]
}
//and
{
  inv: [{ name: "Another Item", amount: 15 }]
}
//and
{
  inv: [{ name: "Some Item", amount: 5 }, { name: "Another Item", amount: 15 }]
}
//and
{
inv: [{ name: "Some Item", amount: 5 }, { name: "Another Item", amount: 15 }, { name: "Different Item", amount: 1 }]
}

但是这些不应该:

{
  inv: [{ name: "Different Item", amount: 1 }]
}
//and
{
  inv: []
}

这对于常规的MongoDB查询很好用,但是对于Mongoose,这是一个问题,因为JavaScript对象中不能有多个相同的属性(在这种情况下为namename) 。我应该如何处理呢?

1 个答案:

答案 0 :(得分:1)

您可能正在寻找$or查询运算符

db.collection.find({ inv: { $elemMatch: { "$or": [ { name: "Some Item" }, { name: "Another Item" } ] } } })