如何在使用MongoDB分页的数据中实现后端搜索?

发布于 2025-01-21 21:10:20 字数 2567 浏览 0 评论 0 原文

我想从分配给用户的SystemID列表中实现同一API中的后端搜索。

将系统(ID)s分配给用户的集合:

{ 
    "_id" : ObjectId("62093266db5c0830fe3397ea"), 
    "email" : "[email protected]",
    "role" : "owner", 
    "systemID" : [
        "12345678", 
        "20200302"
    ], 
    "mobile" : "9876543210"
}

系统ID(BPID)单独存储在另一个包含系统详细信息的集合中。

{ 
    "_id" : ObjectId("6212d42aab85a3b9f7559e02"), 
    "bPID" : "12345678", // primary key
    "bPVoltage" : 45.9,
    "capacity" : "5", 
    "alerts" : [ "201", "342" ],
    "state": 2,
    "stateOfCharge": 98
},
{ 
    "_id" : ObjectId("6212d42bab8ba3d9f7599ea2"), 
    "bPID" : "20200302", 
    "bPVoltage" : 45.9,
    "capacity" : "2", 
    "alerts" : [ "200" ],
    "state": 0,
    "stateOfCharge": 48
},
{ 
    "_id": ObjectId("6212d42aab85a3b9f7559e02"), 
    "bPID": "20200302", 
    "bPVoltage": 45.9,
    "capacity": "5", 
    "alerts": [ "315" ],
    "state": 1,
    "stateOfCharge": 78
}

现在,我有一张桌子在前端,其中分页的数据被填充在桌子内,上面有一个搜索框。

如果我输入ID,如何实现此搜索,它将返回仅分配给该用户的匹配ID的列表,例如,如果我输入12,则返回了12348或12469分配给用户。我的API代码填充结果仅在表中填充的BPID的结果如下:

router.get('/getActiveSystems', async (req, res) => {
  const systemList = req.systemList;
  const { page, limit } = req.query;

  try {
    if (!page || !limit) {
      return res.status(400).json({
        message: 'Page and limit are required!',
        error: true
      });
    }

    const lastTenMinutes = moment().subtract(10, 'm').toDate();

    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      sort: {
        date: -1.0
      }
    };

    const query = [
      {
        $match: {
          bPID: {
            $in: systemList
          },
          date: {
            $gte: new Date(lastTenMinutes)
          }
        }
      },
      {
        $project: {
          bPID: 1.0,
          capacity: 1.0,
          alerts: 1.0,
          state: 1.0,
          stateOfCharge: 1.0
        }
      }
    ];

    const aggregate = BatteryPacks.aggregate(query);
    const systemDetails = await BatteryPacks.aggregatePaginate(aggregate, options);
    return res.status(200).json(systemDetails);
  } catch (error) {
    return res.status(500).json({
      message: 'Internal server error'
    });
  }
});

I want to implement backend search within same API (if possible) from a list of systemIDs assigned to the user.

Collection where system (ID)s are assigned to a user:

{ 
    "_id" : ObjectId("62093266db5c0830fe3397ea"), 
    "email" : "[email protected]",
    "role" : "owner", 
    "systemID" : [
        "12345678", 
        "20200302"
    ], 
    "mobile" : "9876543210"
}

System Ids (bPID) are stored individually inside another collection with current details of the system.

{ 
    "_id" : ObjectId("6212d42aab85a3b9f7559e02"), 
    "bPID" : "12345678", // primary key
    "bPVoltage" : 45.9,
    "capacity" : "5", 
    "alerts" : [ "201", "342" ],
    "state": 2,
    "stateOfCharge": 98
},
{ 
    "_id" : ObjectId("6212d42bab8ba3d9f7599ea2"), 
    "bPID" : "20200302", 
    "bPVoltage" : 45.9,
    "capacity" : "2", 
    "alerts" : [ "200" ],
    "state": 0,
    "stateOfCharge": 48
},
{ 
    "_id": ObjectId("6212d42aab85a3b9f7559e02"), 
    "bPID": "20200302", 
    "bPVoltage": 45.9,
    "capacity": "5", 
    "alerts": [ "315" ],
    "state": 1,
    "stateOfCharge": 78
}

Now I have a table in frontend where paginated data is being populated inside a table and there is a search box above that.

System Table

How to implement search for this if I enter an ID it returns me list of that matching ID assigned only to that user, for example if I enter 12, bPID with 12348 or 12469 is returned but only if it is assigned to the user. My API code to populate the result where only assigned bPIDs are populated in the table is as follows:

router.get('/getActiveSystems', async (req, res) => {
  const systemList = req.systemList;
  const { page, limit } = req.query;

  try {
    if (!page || !limit) {
      return res.status(400).json({
        message: 'Page and limit are required!',
        error: true
      });
    }

    const lastTenMinutes = moment().subtract(10, 'm').toDate();

    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      sort: {
        date: -1.0
      }
    };

    const query = [
      {
        $match: {
          bPID: {
            $in: systemList
          },
          date: {
            $gte: new Date(lastTenMinutes)
          }
        }
      },
      {
        $project: {
          bPID: 1.0,
          capacity: 1.0,
          alerts: 1.0,
          state: 1.0,
          stateOfCharge: 1.0
        }
      }
    ];

    const aggregate = BatteryPacks.aggregate(query);
    const systemDetails = await BatteryPacks.aggregatePaginate(aggregate, options);
    return res.status(200).json(systemDetails);
  } catch (error) {
    return res.status(500).json({
      message: 'Internal server error'
    });
  }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小傻瓜 2025-01-28 21:10:20

如果我正确理解,您可以执行以下操作:

db.users.aggregate([
  {$match: {"_id": user_id}},
  {
    $project: {
      systemIDs: {
        $filter: {
          input: "$systemID",
          as: "item",
          cond: {$regexMatch: {input: "$item",  regex: searchInput}}
        }
      }
    }
  },
  { $unwind: "$systemIDs"},
  {
    $lookup: {
      from: "systemIds",
      localField: "systemIDs",
      foreignField: "bPID",
      as: "systemIds"
    }
  },
  { $sort: { systemIDs: 1}},
  { $skip: 0},
  { $limit: 10}
])

$ match 找到特定用户, $ project filters仅 SystemId 与之匹配的SystemID searchInput和 $查找获得 SystemId 数据。还有其他步骤允许分页(在此示例中有10个结果)。

您可以看到它在 Playground 上有效

If I understand correctly, you can do something like:

db.users.aggregate([
  {$match: {"_id": user_id}},
  {
    $project: {
      systemIDs: {
        $filter: {
          input: "$systemID",
          as: "item",
          cond: {$regexMatch: {input: "$item",  regex: searchInput}}
        }
      }
    }
  },
  { $unwind: "$systemIDs"},
  {
    $lookup: {
      from: "systemIds",
      localField: "systemIDs",
      foreignField: "bPID",
      as: "systemIds"
    }
  },
  { $sort: { systemIDs: 1}},
  { $skip: 0},
  { $limit: 10}
])

Where the $match finds the specific user, the $project filters only systemID that are matching the searchInput, and the $lookup gets the systemID data. The other steps are there to allow the pagination (of 10 results in this example).

You can see it works on the playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文