即使指定了投影,Mongodb 也会返回所有字段

Ben*_*nny 1 regex projection mongodb

更新:

我只想返回适合输入的给定用户名的四个字符的所有文档。因此,如果我有一个用户名列表并输入 mango3333,则应返回所有以“mang”开头的用户名。我为此使用了正则表达式,现在我只想返回例如该文档的用户名和 ID 而不是所有字段,但它返回所有字段。

示例文档如下所示:

{"_id":{"$oid":"5d75299b0d01830"}, 
"User": 
{ "username":"mango",
  "userid":"8b8d25d3-3fe6-4d1c",
  "token":"token",
  "pw":"password",
  "statusmessage":"",
  "lastlogin":{"$date":{"$numberLong":"1567959451354"}},
  "registered":{"$date":{"$numberLong":"1567959451354"}
}
Run Code Online (Sandbox Code Playgroud)

这是我的查询:

const db = dbClient.db(dbName);
const regexp = new RegExp(username, "gi");
db.collection(collectionName).find({ "User.Username": regexp }, { "User.Username": 1, "User.UserID": 1, "User.Statusmessage": 1 })
.toArray()
.then(result => {
  console.log(result);
})
.catch(err => console.error(`Failed to get results: ${err}`));
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Ada*_*son 5

find方法的第二部分是一个选项对象,而不仅仅是投影。需要在此options对象中指定查询的投影部分。请尝试以下操作:

db.collection(collectionName).find(
  { "User.Username": regexp }, 
  { 
     projection: { 
       "User.Username": 1, 
       "User.UserID": 1, 
       "User.Statusmessage": 1 
     }
  }
)
.toArray()
.then(result => {
  console.log(result);
})
Run Code Online (Sandbox Code Playgroud)

https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#find