Mongo数据库搜索就像查询一样,但是在子数组中有标准

时间:2022-07-07 18:16:34

Hi I have this kind of object.

嗨,我有这种对象。

{
    "_id" : "wavQwJn5ZGQw2sTqb",
    "createdAt" : ISODate("2015-12-15T13:55:21.526Z"),
    "services" : {
        "password" : {
            "bcrypt" : "passhash"
        },
        "resume" : {
            "loginTokens" : [ 
                {
                    "when" : ISODate("2015-12-15T13:56:48.837Z"),
                    "hashedToken" : "tokenhash"
                }
            ]
        }
    },
    "profile" : {
        "name" : "First Name LastName"
    },
    "emails" : [ 
        {
            "address" : "myemail1@domain.com",
            "verified" : false
        },
        {
            "address" : "myemail2@domain.com",
            "verified" : false
        }
    ]
}

I have to search for users by their email or profile name, but this email is in subarray and each element there is an little object and profile is an object, so I got really confused here.

我必须通过他们的电子邮件或个人资料名称搜索用户,但是这封电子邮件是在子阵列中,每个元素都有一个小对象和个人资料是一个对象,所以我真的很困惑。

For example if email was in the main object I can do this:

例如,如果电子邮件在主对象中,我可以这样做:

let selector = {
    'email' : { '$regex' : '.*' + searchString || '' + '.*', '$options' : 'i' },
}

Meteor.users.find(selector, options);   

but unfortunaly is in subarray, so if someone can explain how I can do that would be great. Thank you in advance.

但不幸的是在子阵列中,所以如果有人可以解释我怎么做,那将是伟大的。先谢谢你。

1 个解决方案

#1


0  

Here, you can search email using aggregation framework.

在这里,您可以使用聚合框架搜索电子邮件。

$unwind operator helps you.

$ unwind运算符可以帮助您。

db.collection.aggregate([{$unwind:'$emails'},{$match:{'emails.address':{$eq:'myemail1@domain.com'}}}]);

Document for reference: MongoDB unwind docs

供参考的文档:MongoDB展开文档

#1


0  

Here, you can search email using aggregation framework.

在这里,您可以使用聚合框架搜索电子邮件。

$unwind operator helps you.

$ unwind运算符可以帮助您。

db.collection.aggregate([{$unwind:'$emails'},{$match:{'emails.address':{$eq:'myemail1@domain.com'}}}]);

Document for reference: MongoDB unwind docs

供参考的文档:MongoDB展开文档