【问题标题】:Unable to select specific field for MongoDB find operation无法为 MongoDB 查找操作选择特定字段
【发布时间】:2021-12-23 23:28:40
【问题描述】:

我试图从 mongo 文档中只选择一个字段并打印它的值。我找到了这个答案https://stackoverflow.com/a/25589150,它展示了我们如何实现这一目标。下面我尝试做同样的事情,但整个文档最终都被打印出来了。

const mongoHost =
  'somemongourl'
const mongodb = require('mongodb');
const { MongoClient } = mongodb;

MongoClient.connect(
  mongoHost,
  { useNewUrlParser: true },
  async (error, client) => {
    if (error) {
      return console.log('Unable to connect to database!');
    }
    const db = client.db('cartDatabase');

    const values = await db
      .collection('cart')
      .find({ customer_key: 'c_1' }, { customer_key: 1, _id: 0 })
      .toArray();

    console.log(values);
  }
);

这是我得到的输出示例:-

[
  {
    _id: new ObjectId("611b7d1a848f7e6daba69014"),
    customer_key: 'c_1',
    products: [ [Object] ],
    coupon: '',
    discount: 0,
    vat: 0,
    cart_total: 999.5,
    cart_subtotal: 999.5
  }
]

这是我所期待的 -

[
  {
    customer_key: 'c_1'
  }
]

【问题讨论】:

  • options 参数可能需要顶级 projection 属性。请改用{projection: {customer_key: 1, _id: 0}}
  • 非常感谢@B.Fleming 这解决了我的问题。我应该将此添加为答案并接受吗?
  • 另外,我曾尝试搜索其他一些资源,例如 docs.mongodb.com/manual/tutorial/…。但是找不到投影键的提及,然后将选项分配为值。我在哪里可以找到这方面的文档?
  • 我将使用相关文档添加完整、正确的答案:)

标签: node.js mongodb mongodb-query


【解决方案1】:

如果您希望投影文档,标准的 Node.js MongoDB 驱动程序需要一个顶级的 projection 属性作为 options 参数。这将导致您的find() 调用的第二个参数如下所示:

{ projection: { customer_key: 1, _id: 0 } }

Node.js MongoDB 驱动程序 API 文档中指出了这一点,这与 MongoDB shell API 并不是一对一的匹配。

截至本答案发布时,您可以找到 collection.find() 参考 here。此参考显示了以下方法签名(同样在编写此答案时):

find(filter: Filter<WithId<TSchema>>, options?: FindOptions<Document>)

跟随FindOptions 参数将我们带到this reference page,它详细说明了find() 方法可用的各种顶级选项属性。其中包括有问题的projection 属性。

简而言之,不要将普通的 MongoDB 文档用作您的编程语言的 MongoDB 驱动程序 API 的参考。两者之间经常会出现脱节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2019-12-25
    • 2021-03-06
    相关资源
    最近更新 更多