在Field Projection中忽略batchSize字段名称 [英] batchSize field name ignored in Field Projection

查看:107
本文介绍了在Field Projection中忽略batchSize字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个user_batch集合。它包含以下文件:

I have a user_batch collection. It contains following documents:

[{
  _id: ObjectId("594baf96256597ec035df23c"),
  name: "Batch 1",
  batchSize: 30,
  users:[]
 },
 {
  _id: ObjectId("594baf96256597ec035df234"),
  name: "Batch 2",
  batchSize: 50,
  users:[]
 }]

在查找查询中,我只想投影名称 batchSize 。但是当我从nodejs执行查询查询时,我在查询结果中获取整个文档。查询:

In find query I want to project only name and batchSize. But when I execute find query from nodejs, I'm getting entire document in query result. Query:

db.collection('user_batch').find({}, {name: 1, batchSize: 1}).toArray((err, result) => {
  if(err) 
    console.log(err)
  else
    console.log(result)
})

如果我只是通过 {name:1} 那么它将投射_id和名字。但是如果我传递 batchSize 那么它将返回整个文档。

If I just pass {name: 1} then it will project _id and name. But if I pass batchSize then it will return entire document.

注意:我在Mongo Shell中执行此查询时没有遇到此问题

Note: I'm not facing this issue while executing this query in Mongo Shell

推荐答案

你是正确的,驱动程序错误地将其解释为 batchSize 选项并忽略投影语句。

You are correct that the driver incorrectly interprets this as the batchSize option and ignores the projection statement.

在现代驱动程序版本中,正确使用 .project() cursor method代替。这与其他语言驱动程序实现更加一致。

The correct way to do this though in modern driver releases is to actually use the .project() "cursor method" instead. This is more consistent with other language driver implementations.

    db.collection('collection').find()
      .project({ name: 1, batchSize: 1})
      .toArray();

作为完整演示:

const mongodb = require('mongodb'),
      MongoClient = mongodb.MongoClient;


(async function() {

  let db;

  try {
    db = await MongoClient.connect('mongodb://localhost/test');

    // New form uses .project() as a cursor method
    let result = await db.collection('collection').find()
      .project({ name: 1, batchSize: 1})
      .toArray();

    console.log(JSON.stringify(result,undefined,2));

    // Legacy form confuses this as being a legacy "cursor option"
    let other = await db.collection('collection')
      .find({},{ name: 1, batchSize: 1 })
      .toArray();

    console.log(JSON.stringify(other,undefined,2));

  } catch(e) {
    console.error(e)
  } finally {
    db.close()
  }

})()

产生输出:

[
  {
    "_id": "594baf96256597ec035df23c",
    "name": "Batch 1",
    "batchSize": 30
  },
  {
    "_id": "594baf96256597ec035df234",
    "name": "Batch 2",
    "batchSize": 50
  }
]
[
  {
    "_id": "594baf96256597ec035df23c",
    "name": "Batch 1",
    "batchSize": 30,
    "users": []
  },
  {
    "_id": "594baf96256597ec035df234",
    "name": "Batch 2",
    "batchSize": 50,
    "users": []
  }
]

第一个使用 .project()

Where the first output form is the corrected one, using .project()

这篇关于在Field Projection中忽略batchSize字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆