查询带有给定子字段值的文档的Mongo(仅限此值)

时间:2016-08-01 06:34:04

标签: mongodb-query

Mongo集合包含以下文档:

{
  name: containerA,
  tasks: [
    {name: taskA1, foo: bar, status: active}
    {name: taskA2, foo: bar, status: ready}
}
{
  name: containerB,
  tasks: [
    {name: taskB1, foo: bar, status: active}
    {name: taskB2, foo: bar, status: done}
    {name: taskB3, foo: bar, status: failure}
}
{
  name: containerC,
  tasks: [
    {name: taskC1, foo: bar, status: failure}
    {name: taskC2, foo: bar, status: done}
    {name: taskC3, foo: bar, status: done}
}

我需要一个只返回带有 foo = bar 的已完成容器 containerC 的查询。 "成品"表示 status = done status = failure

查询

db.container.find({
  tasks: {
    $elemMatch: {
      foo: "bar",
      status: {$in: ["done", "failure"]}
    }
  }
})

还返回 containerB :(

谢谢

2 个答案:

答案 0 :(得分:0)

status指定另一个匹配器,以排除您不想要的值

db.container.find({
  tasks: {
    $elemMatch: {
      foo: "bar",
      status: {
         $in: ["done", "failure"],
         $nin: ["active", "ready"]
      }
    }
  }
})

答案 1 :(得分:0)

db.container.find({'tasks.status':{$nin:['active', 'ready']}}, {_id:0, name:1})