简体   繁体   English

猫鼬查找查询与$ match

[英]Mongoose find query vs $match

I have a following document inside mongodb 我在mongodb中有以下文件

{
    "_id" : ObjectId("5a25f1b19c72e07ffc50a37d"),
    "name" : "test",
    "category" : ObjectId("5a1e6622a7739fb64c8c530b"),
    "recentDeveloperComment" : ObjectId("5a25f1b19c72e07ffc50a37c"),
    "fileName" : "test2.xlsx",
    "rawData" : ObjectId("5a21079ef99e75b2140fb77a"),
    "group" : {
        "year" : 2017,
        "month" : 1,
        "category" : "test1"
    },
    "unlocked" : false,
    "status" : "Pending",
    "updatedAt" : ISODate("2017-12-05T01:08:40.465Z"),
    "createdAt" : ISODate("2017-12-05T01:08:40.465Z"),
    "__v" : 0
}

I can match this by using following find query with mongoose 我可以通过以下搜索查询与猫鼬匹配

Repo.find({'group.year' : year, 'group.month' : month, 'group.category' : category, name:repo})
    .exec((err, repoResult) => {
        //matches one document
    })

However with the below aggregate $match I cannot get the same result 但是,使用下面的总计$ match,我无法获得相同的结果

Repo.aggregate([
    {
        $match:
            {
                $and:[
                    {'group.year' : year},
                    {'group.month' : month},
                    {'group.category' : category},
                    {name : repo}
                ]
            }
    },
]).exec((err, commitsResult) => {
    //matches zero document
});

Why is this? 为什么是这样?

It was because find parses all the query strings into the variable type that is defined in the database. 这是因为find将所有查询字符串解析为数据库中定义的变量类型。 For example year was a parameter parsed from url so it was a string form but in Mongodb the field is defined as an int. 例如, year是从url解析的参数,因此它是字符串形式,但是在Mongodb中,该字段定义为int。 Find automatically parses this to the correct type but $match does not parse it so it has to be done manually. Find自动将其解析为正确的类型,但是$match不会对其进行解析,因此必须手动完成。

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

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