问题描述
我在 mongodb 中有以下文档
I have a following document inside 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
}
我可以通过使用下面的 mongoose 查找查询来匹配这个
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
})
但是使用下面的聚合 $match 我不能得到相同的结果
However with the below aggregate $match I cannot get the same result
Repo.aggregate([
{
$match:
{
$and:[
{'group.year' : year},
{'group.month' : month},
{'group.category' : category},
{name : repo}
]
}
},
]).exec((err, commitsResult) => {
//matches zero document
});
这是为什么?
推荐答案
这是因为 find
将所有查询字符串解析为数据库中定义的变量类型.例如 year
是一个从 url 解析出来的参数,所以它是一个字符串形式,但在 Mongodb 中,该字段被定义为一个 int.Find
会自动将其解析为正确的类型,但 $match
不会解析它,因此必须手动完成.
It was because find
parses all the query strings into the variable type that is defined in the database. 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. Find
automatically parses this to the correct type but $match
does not parse it so it has to be done manually.
这篇关于猫鼬查找查询与 $match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!