如何使用Node.JS在MongoDB中正确实现过滤器和/或投影

bakd9h0s  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(317)

我在一个名为user_records的集合(表)中有一个非常简单的文档(行)结构,如下所示:

  1. [
  2. {
  3. _id: new ObjectId("652edd74bdb84c9944d280d6"),
  4. customer_id: 1001,
  5. first_name: 'Test',
  6. last_name: 'User',
  7. username: 'Tuser',
  8. password: 'Testuser',
  9. registration_date: 2023-10-17T13:54:54.000Z
  10. }
  11. ]

字符串
我想运行一个只返回customer IDfirst namelast nameusername的查询,其中username = username。然而,我尝试过的所有查询都只返回完整的文档(行)。
我的第一次尝试是这个,主要受到MongoDB Compass AI的启发:
1.我为查询定义了过滤器和投影参数:

  1. // Define query parameters
  2. const filter = { 'username': username };
  3. const projections = {
  4. '_id': 0,
  5. 'customer_id': 1,
  6. 'first_name': 1,
  7. 'last_name': 1,
  8. 'username': 1,
  9. 'password': 0,
  10. 'registration_date': 0
  11. };


1.我构建了查询:

  1. const customersCollection = client.db('customer_data').collection('user_records');
  2. const customer = await customersCollection.find(filter, projections).toArray();


为了让它发挥作用,我还尝试了一些修改:

  • 从投影对象的关键点中删除''
  • projections作为对象传递给.find。就像.find(filter, { projections })一样。
  • 使用findOne代替。

以上都不起作用。
我的第二次尝试更加复杂。我没有定义projections对象,而是这样做:

  1. const customersCollection = client.db('customer_data').collection('user_records');
  2. const customer = await customersCollection.aggregate([
  3. { $match: filter },
  4. {
  5. $project: {
  6. '_id': 0,
  7. 'customer_id': 1,
  8. 'first_name': 1,
  9. 'last_name': 1,
  10. 'username': 1,
  11. 'password': 0,
  12. 'registration_date': 0
  13. }
  14. }
  15. ]).toArray();


这没有返回任何东西。
在所有这些中,我只是想让customer来保存这个:

  1. [
  2. {
  3. customer_id: 1001,
  4. first_name: 'Test',
  5. last_name: 'User',
  6. username: 'Tuser',
  7. }
  8. ]


我几天前才开始使用MongoDB,来自MySQL;任何形式的帮助都将受到赞赏。

mbzjlibv

mbzjlibv1#

总的来说,我认为我们需要更多的调试细节。
假设在第一次尝试中username变量被设置为字符串'Tuser',它甚至不会运行,因为它混淆了“包含”和“排除”投影。你可以看到this playground example中的错误。
我们不知道你第二次尝试的filter变量是什么。如果我假设它类似于{ username: 'Tuser' },那么它也会因为格式错误的投影而失败。你可以在this playground example中看到。
你确定你共享的(重新编译的?)代码/查询是发送到数据库的吗?
在任何情况下,你需要做一个包含投影,同时也抑制_id字段。这需要从你的投影中删除最后两行,例如:

  1. db.collection.find({
  2. "username": "Tuser"
  3. },
  4. {
  5. "_id": 0,
  6. "customer_id": 1,
  7. "first_name": 1,
  8. "last_name": 1,
  9. "username": 1
  10. })

字符串
当您对包含这两个文档集合运行查询时:

  1. [
  2. {
  3. _id: ObjectId("652edd74bdb84c9944d280d6"),
  4. customer_id: 1001,
  5. first_name: "Test",
  6. last_name: "User",
  7. username: "Tuser",
  8. password: "Testuser",
  9. registration_date: new Date("2023-10-17T13:54:54.000Z")
  10. },
  11. {
  12. username: "other"
  13. }
  14. ]


输出为:

  1. [
  2. {
  3. "customer_id": 1001,
  4. "first_name": "Test",
  5. "last_name": "User",
  6. "username": "Tuser"
  7. }
  8. ]


这似乎是你所要求的。看看它在this playground example中是如何工作的。

展开查看全部

相关问题