代码之家  ›  专栏  ›  技术社区  ›  philip yoo

节点mongodb 3.4使用find with specify fields和toArray不会过滤结果[重复]

  •  1
  • philip yoo  · 技术社区  · 6 年前

    同样,使用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 领域

    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

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    使用 .project

    db.collection('collection')
      .find({ '_id': { '$nin': [Ace, Bay] }, 'value.someCategory': { '$type': 'object' }})
      .project({ '_id': 0, 'value.someCategory': 1 })
      .toArray()
    
        2
  •  0
  •   Raunik Singh    6 年前

    使用“选择”功能并定义要投影的所需字段。

    const m = await Model.find({
            '_id': {
                $nin: [Ace, Bay],
            },
            'value.someCategory': {
                $type: 'object',
            },
        }).select('-_id value.someCategory').lean();
    
    console.log(m)