查询具有大量 objectId 的数组的最佳方法是什么
What is the optimal way of querying array with a lot of objectIds
我有一个 MongoDB 对象 ID 数组,我想将其发送到我的 nodejs 服务器以获取对象数据。
问题是这个数组包含数百个 ID,我不确定我应该如何获取和查询它,因为将它连接到查询字符串是行不通的,因为最大 URL 最多可以有 2048 个字符。
您可以执行以下操作:
如果数据库中的记录按_id排序
在POST
请求中发送一个Id数组或者在GET
请求中的查询参数中只发送最小和最大Id。
相反,查询个人 Id(objectId) 或执行 {$in : [ObjectId( )... ObjectId.....]}
如下所述。
使用数组中的最小和最大 ID,像这样查询数据库:
User.find({"_id":{$lte: idmax,$gte:idmin}})
如果记录未按 _id 排序:
User.find({"_id":{$in:[_id1,id_2.....]})
PS: Learn more about range queries.
The relationship between the order of ObjectId values and generation
time is not strict within a single second. If multiple systems, or
multiple processes or threads on a single system generate values,
within a single second; ObjectId values do not represent a strict
insertion order. Clock skew between clients can also result in
non-strict ordering even for values, because client drivers generate
ObjectId values, not the mongod process. So if this is a case you will
have to query using in operator {$in : [ObjectId( ). ObjectId.....]}
Long story short: If ids are not in the order in DB you will have to use
the in
operator because otherwise, the range query will fetch
extra-record.
我有一个 MongoDB 对象 ID 数组,我想将其发送到我的 nodejs 服务器以获取对象数据。 问题是这个数组包含数百个 ID,我不确定我应该如何获取和查询它,因为将它连接到查询字符串是行不通的,因为最大 URL 最多可以有 2048 个字符。
您可以执行以下操作:
如果数据库中的记录按_id排序
在
POST
请求中发送一个Id数组或者在GET
请求中的查询参数中只发送最小和最大Id。相反,查询个人 Id(objectId) 或执行
{$in : [ObjectId( )... ObjectId.....]}
如下所述。使用数组中的最小和最大 ID,像这样查询数据库:
User.find({"_id":{$lte: idmax,$gte:idmin}})
如果记录未按 _id 排序:
User.find({"_id":{$in:[_id1,id_2.....]})
PS: Learn more about range queries.
The relationship between the order of ObjectId values and generation time is not strict within a single second. If multiple systems, or multiple processes or threads on a single system generate values, within a single second; ObjectId values do not represent a strict insertion order. Clock skew between clients can also result in non-strict ordering even for values, because client drivers generate ObjectId values, not the mongod process. So if this is a case you will have to query using in operator
{$in : [ObjectId( ). ObjectId.....]}
Long story short: If ids are not in the order in DB you will have to use the
in
operator because otherwise, the range query will fetch extra-record.