首页 > 解决方案 > node mongodb 3.4 使用带有指定字段的 find 和 toArray 不过滤结果

问题描述

同样,使用 mongo v3.4 并引用这些文档:https ://docs.mongodb.com/v3.4/tutorial/project-fields-from-query-results/

我的示例如下所示:

    const m = this.getCollection(SOME_COLLECTION);
    m.find({
        '_id': {
            $nin: [Ace, Bay],
        },
        'value.someCategory': {
            $type: 'object',
        },
    }, {
        '_id': 0,
        'value.someCategory': 1,
    }).toArray((err, doc) => {
        if (err) {
            console.log(err);
        } else {
            console.log(doc);
        }
    });

我的doc数组将返回遵循我value.someCategory的对象类型过滤器的所有项目,但不会删除_id并且将返回所有字段,即使我只想指定value.someCategory字段。

mongo 中的示例数据:

[
    {
      _id: 'hello',
      value: {
        someCategory: [Object],
        name: 'hello',
        otherCategory: true,
      }
    },
    {
      _id: 'Ace',
      value: {
        someCategory: [Object],
        name: 'Ace',
        otherCategory: true,
      }
    },
    {
      _id: 'testing',
      value: {
        someCategory: null,
        name: 'testing',
        otherCategory: true,
      }
    },
]

并期望结果是:

[
    {
      someCategory: [Object],
    },
]

根据上面链接的文档,指定的字段应该是第二个参数。我现在想知道使用是否toArray会影响返回值?

标签: node.jsmongodbmongodb-query

解决方案


改用.project游标方法

db.collection('collection')
  .find({ '_id': { '$nin': [Ace, Bay] }, 'value.someCategory': { '$type': 'object' }})
  .project({ '_id': 0, 'value.someCategory': 1 })
  .toArray()

推荐阅读