【问题标题】:Mongodb returns all fields even with projection specified即使指定了投影,Mongodb 也会返回所有字段
【发布时间】:2020-01-12 16:16:18
【问题描述】:

更新:

我只想返回符合输入的给定用户名的四个字符的所有文档。因此,如果我有一个用户名列表并输入 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"}
}

这是我的查询:

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}`));

我做错了什么?

【问题讨论】:

  • 这是关于如何在 mongdb 查询中定义正则表达式,这部分对我来说很好用,我的问题是只返回文档中的特定字段而不是所有字段
  • 您认为 OP 如何提供可重现的示例? @JohnnyHK 代码 sn-p 不够好吗?任何人,you can try something like this,因为它适用于那个人(和你有同样的问题)......
  • @MattOestreich 这个解决方案有效,谢谢!

标签: regex mongodb projection


【解决方案1】:

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);
})

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 2021-03-09
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多