用$ Elemmatch查询返回意外结果

发布于 2025-01-24 12:59:33 字数 1405 浏览 0 评论 0原文

我有以下文件:

  {
    _id: ObjectId("6266d9ad44d8051197ac7507"),
    aircraftCode: '1b7ad0de-5836-489b-9791-5a81a51cdb81',
    crew: [
      {
        name: 'Nina Peltier',
        position: 'Attendant',
        nationality: 'France',
        hoursSlept: 6
      },
      {
        name: 'Lou Galopin',
        position: 'Attendant',
        nationality: 'France',
        hoursSlept: 7
      }
    ]
  },
  {
    _id: ObjectId("6266d9ad44d8051197ac7508"),
    crew: [ { name: 'Popescu Ion', position: 'Captain', hoursSlept: 8 } ]
  },
  {
    _id: ObjectId("6266d9ad44d8051197ac7509"),
    aircraftCode: 'eede6be6-f716-4e2e-bf81-885f0a16a50c',
    crew: [
      {
        name: 'Pierre Cotard',
        position: 'Captain',
        nationality: 'France',
        hoursSlept: 4
      },
      { name: 'Amanda Lucas', position: 'Attendant', hoursSlept: 6 },
      {
        name: 'Joe Stan',
        position: 'Attendant',
        nationality: 'UK',
        hoursSlept: 8
      }
    ]
  }

我只想找到那些不在船员中的“队长”的文件。

这起作用:

db.flights.find({ "crew.position": { $ne: "Captain" }  })

这无效:

db.flights.find({ crew: { $elemMatch: { position: { $ne: "Captain" } } } })

它还返回了船长在场的文档。

我的第二个查询怎么了?

I have the following documents:

  {
    _id: ObjectId("6266d9ad44d8051197ac7507"),
    aircraftCode: '1b7ad0de-5836-489b-9791-5a81a51cdb81',
    crew: [
      {
        name: 'Nina Peltier',
        position: 'Attendant',
        nationality: 'France',
        hoursSlept: 6
      },
      {
        name: 'Lou Galopin',
        position: 'Attendant',
        nationality: 'France',
        hoursSlept: 7
      }
    ]
  },
  {
    _id: ObjectId("6266d9ad44d8051197ac7508"),
    crew: [ { name: 'Popescu Ion', position: 'Captain', hoursSlept: 8 } ]
  },
  {
    _id: ObjectId("6266d9ad44d8051197ac7509"),
    aircraftCode: 'eede6be6-f716-4e2e-bf81-885f0a16a50c',
    crew: [
      {
        name: 'Pierre Cotard',
        position: 'Captain',
        nationality: 'France',
        hoursSlept: 4
      },
      { name: 'Amanda Lucas', position: 'Attendant', hoursSlept: 6 },
      {
        name: 'Joe Stan',
        position: 'Attendant',
        nationality: 'UK',
        hoursSlept: 8
      }
    ]
  }

I want to find only those where 'Captain' is not in the crew.

This works:

db.flights.find({ "crew.position": { $ne: "Captain" }  })

This doesn't work:

db.flights.find({ crew: { $elemMatch: { position: { $ne: "Captain" } } } })

It returns also documents where the captain is present.

What's wrong with my second query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文