【问题标题】:Mongoose find query vs $matchMongoose 查找查询与 $match
【发布时间】:2018-05-18 14:31:48
【问题描述】:

我在 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 的 find 查询来匹配它

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

但是,使用以下汇总 $match 我无法得到相同的结果

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

这是为什么?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    这是因为find 将所有查询字符串解析为数据库中定义的变量类型。例如year 是从 url 解析的参数,因此它是一个字符串形式,但在 Mongodb 中,该字段被定义为一个 int。 Find 会自动将其解析为正确的类型,但 $match 不会对其进行解析,因此必须手动完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多