繁体   English   中英

查找包含子对象MongoDb和Node.js的某些字段的文档

[英]Find documents that contain certain field for sub-object MongoDb and Node.js

我有以下格式的集合:

[ 
  {
     firstname: 'Joe',
     lastname: 'Blow',
     emails: [
       {
          email: 'test@example.com',
          valid: false
       },
       {
          email: 'test2@example.com',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d94a
  },
  {
     firstname: 'Johnny',
     lastname: 'Doe',
     emails: [
       {
          email: 'test3@example.com',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d87b
  },
]

我正在尝试根据emails.email字段查找用户。 这是我到目前为止的内容:

db.collection('users').aggregate([
    {$unwind: "$emails"},
    {$group: {_id: "$_id",user_emails: { $push: "$emails.email" } } },
    {$match: {'user_emails': { $in: ['test@example.com'] } } }
  ], 
  (error, result) => {
    console.log(error);
    console.log(result);
  }
);

当我在mongo shell中运行此命令时,它似乎可以工作; 但是,当我在Node.js运行它时,它会为错误输出null并为结果输出[]

我究竟做错了什么? 我对MongoDB相当MongoDB ,只是似乎无法弄清楚。

为什么要撤消所有电子邮件? 当您的收藏随着大量记录增长时,这将是一个非常昂贵的操作。

以下查询将向用户返回电子邮件test2@example.com。 我认为这就是您想要的东西吗?

db.email.find({emails :{$elemMatch:{email:"test2@example.com"}}})

我将您的代码稍作改动重新编写了。

var col = db.collection('collection');
if (col) {
    col.aggregate([
        {$unwind: "$emails"},
        {$group: {_id: "$_id",user_emails: { $push: "$emails.email" } } },
        {$match: {'user_emails': { $in: ['test@example.com'] } } }
    ], function(e, r){
        if(e){
            console.log(error);
        }

        console.log(r);
        db.close();
    });
}

只要您已成功建立连接和其他要求,它就可以工作。 提供您的样本文档,它将发出:

[
    {
        _id: '57017e173915101e0ad5d94a',
        user_emails: [
            'test@example.com',
            'test2@example.com'
        ]
    }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM