【问题标题】:Match not working in MongoDB. Match is returning an empty array匹配在 MongoDB 中不起作用。匹配返回一个空数组
【发布时间】:2021-06-20 08:30:52
【问题描述】:

我正在尝试创建一个聚合管道。代码的开头工作正常。但是当涉及到 $match 时,代码什么也不返回。这是我的代码:

    var userId = req.params.UserId
    const measure = await Measure.aggregate([
        {
            $project: {
                user: 1, creationDate: 1, WaterConsumption: 1
            }
        }, 
        {
            $match: {
                user: userId
            }
        },
        {
            $group: {
                _id: {
                    $dayOfMonth: "$creationDate"
                },
                waterConsumption: {$sum :  "$WaterConsumption"}
            }
        }
    ]);
    return res.json({measure})

我的数据是:

{
  "measures": [
    {
      "creationDate": "2021-03-19T10:25:05.674Z",
      "_id": "605870bffa87a605bf2a983a",
      "avgPower": 8241,
      "WaterConsumption": 22,
      "avgTemperature": 45,
      "shower": "5fb56ce7734b7e04b9c97c9b",
      "user": "5f6cb0496a8c5a0deaa1a746"
    },
    {
      "creationDate": "2021-03-19T10:25:05.674Z",
      "_id": "605870d9fa87a605bf2a983b",
      "avgPower": 8241,
      "WaterConsumption": 22,
      "avgTemperature": 45,
      "shower": "5fb56ce7734b7e04b9c97c9b",
      "user": "5f6cb0496a8c5a0deaa1a746"
    },
    {
      "creationDate": "2021-03-17T10:25:05.674Z",
      "_id": "605870ebfa87a605bf2a983c",
      "avgPower": 4300,
      "WaterConsumption": 32,
      "avgTemperature": 28,
      "shower": "5fb56d04734b7e04b9c97c9c",
      "user": "5f6cb0496a8c5a0deaa1a746",
    }...
  ]

代码运行完美,直到达到 $match。如果我控制我的 userId,它是一个用户值为“5f6cb0496a8c5a0deaa1a746”的字符串。我不知道为什么 $match 不起作用。 $group 运行良好。 我试图将匹配交换为 $match:{user: req.params.UserId} 但代码一直返回一个空数组。

【问题讨论】:

    标签: javascript mongodb mongoose aggregation-framework


    【解决方案1】:

    您正在尝试将字符串与 ObjectID 匹配,这就是您的 $match 不起作用的原因。

    ObjectId

    使用 ObjectID 的工作演示 - https://mongoplayground.net/p/Oz95gFwvp9X

    const mongodb = require('mongodb');
    const ObjectID = mongodb.ObjectID;
    const userId = ObjectID(req.params.UserId); // convert your userid to ObjctedID format
    

    例如 - userId - 5f6cb0496a8c5a0deaa1a746 将转换为 ObjectId("5f6cb0496a8c5a0deaa1a746")

    不使用字符串 - https://mongoplayground.net/p/5PN8WeXt2zc

    【讨论】:

    • 这是我的伙伴!工作就像一个魅力,感谢您的帮助。
    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2019-04-28
    • 2021-07-28
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    相关资源
    最近更新 更多