首先也是最重要的是,我已经很长时间没有做开发了,更不用说使用Mongo了,但我还没有找到一个解决方案来解决一个可能很简单的问题.

在上下文中,我正在try 获取嵌套对象的ID以备将来使用.客户集合如下所示:

{
  "_id": ObjectId("1223334abc"),
  "mainNumber": "123",
  "notificationAccount" : [
      "channel": "Apple",
       "notificationAccountId": "700002",
        ]
}

我有一个包含mainNumbers个帐户的数组,并试图将所有匹配的帐户放入一个空数组中.所以现在看起来是这样的:

mainNumbers =  ["123", "234", "345", etc]

accountIds = [];
for(mainNumber of mainNumbers){
 customerProfile = db.getCollection("customers").find({mainNumber})
 if (customerProfile != null {
  customerProfile.map(function(singleCustomerProfile){
   accountIds.push(singleCustomerProfile.notificationAccount.notificationAccountId);
   print('${mainNumber} ${singleCustomerProfile.notificationAccount.notificationAccountId}');
   });

 } else }
    print(''${mainNumber} was not found.);
    
    } 
}

这将打印出所有mainNumbers个没有身份证.所以我拿出打印行,所以:

customerProfile.map(function(singleCustomerProfile){
 accountIds.push(singleCustomerProfile.notficiationAccount.notificationAccountId);
});
 print('${mainNumber} - ${accountIds}')

没有错误,但我只是一遍又一遍地得到mainNumber分.

我感觉像是:

  1. 我错过了一些简单的对notificationAccount和我的try 是徒劳的
  2. 可能有一种更好/更干净的方法来在查询时获得数组的DO输出.

欢迎任何帮助.

推荐答案

首先,需要等到数据出来.此外,您还可以通过使用$in方法使用一个find查询来简化请求,因为您有一个数组,并且希望通过该数组获得所有匹配的文档.另外,返回notificationAccount字段会很好,如下所示,因为在这里只需要使用一个特定的字段.

返回响应后,映射响应并将通知ID存储在一个变量中.
我猜,notificationAccount字段是object,所以我是这样映射的.但是,如果它是一个数组,则需要获取map函数中的第一个元素的notificationAccountId.

mainNumbers =  ["123", "234", "345", etc];

const notificationAccounts = await db.getCollection("customers").find(
       { mainNumber: { $in: mainNumbers }}, 
       {"notificationAccount":1, "_id": 0}
);

const accountIds = notificationAccounts.map(({ notificationAccount }) => notificationAccount.notificationAccountId);

我还创建了一个测试演示,您可以在这里轻松地测试它:https://www.mycompiler.io/view/328rl8RTDr1

希望它是清晰和有用的

Mongodb相关问答推荐

如何在MongoDB中使用Aggregation来计算两个键相同但字段不同的对象数组的总值,并将其合并为一个?

如何在Mongo中制作全覆盖索引

在数组对象 Mongodb 中仅 Select 需要的数组

MongoDB Aggregate 根据时间进行多重分组

使用Go的Mongo驱动程序,从MongoDB文档中获取元素并更新其值需要帮助

如何匹配 MongoDB 中同一文档中两个字段的比较?

Mongoose updateMany 以及 Where 和 orWhere?

MongoDB 按 created_at 月聚合

如何为具有相同名称的嵌套字段创建文本索引

@DynamicPropertySource 未被调用(Kotlin、Spring Boot 和 TestContainers)

mongodb - 查找包含至少 3 个填充数组的记录

在亚马逊 EC2 上托管 nodeJS/mongoose Web 应用程序

使用 Node.js 通过 SSL 连接到 MongoDB

Spring Boot MongoDB 连接问题

嵌套在文档数组中的mongodb展开数组

在 Mongo 中存储嵌套类别的最有效方法?

`fields cannot be identical'和''` mongoimport错误

MongoDB - 文件大小巨大且不断增长

MongoError:Topology is closed, please connect despite established database connection

MongoDB 的 MMAPV1、WiredTiger 或 In-Memory StorageEngine 如何 Select ?