首页 > 解决方案 > 在投影中使用 $elemMatch 并选择字段

问题描述

我正在尝试仅选择文档中的某些字段,同时还使用 $elemmatch。事实证明,字段选择被忽略了。

给定这样的文件:

{
  "author": "Robin Sharma",
  "data": [
    {
      "translation": "en",
      "content": "foo",
      "unwanted_content": "huyu1",
    },
    {
      "translation": "id",
      "content": "bar",
      "unwanted_content": "huyu2",
    {
  ],
}

我正在使用find()这个投影配置:

const projection = {
  author: 1,
  data: {
    $elemMatch: {
      translation: "en"
    },
  },
}

预期的

{
  "author": "Robin Sharma",
  "data": [
    {
      "translation": "en",
      "content": "foo"
    },
  ],
}

实际的

{
  "author": "Robin Sharma",
  "data": [
    {
      "translation": "en",
      "content": "foo",
      "unwanted_content": "huyu1",
    },
  ],
}

我仍然不确定如何摆脱“unwanted_content”字段。

标签: mongodbmongoose

解决方案


我认为您可以这样做以仅从子文档中获取选定的字段。

db.collection.find({"data.translation": "en"},{author: 1, "data.content": 1, "data.translation": 1})

推荐阅读