【问题标题】:Get 'n' number of documents started from specific document in MongoDB collection从 MongoDB 集合中的特定文档开始获取“n”个文档
【发布时间】:2021-10-27 07:39:12
【问题描述】:

这是否可以从集合中获取n 数量的文档,并且应该从特定对象开始获取。例如如果一个集合有 100 个文档,那么我需要从 46 [特定 id] 开始的 10 个文档。即 46-55

return new Promise((resolve, reject) => {
  return products_model.find({'from_id' : 9677270841774}).limit(limit).exec((err, records) => {
    if(err)
        reject(err)
    else    
        resolve(records)
  })
})

编辑:原文档结构如下:

{ 
    "_id" : ObjectId("6128a0d9cf34c208c30e6800"), 
    "id" : 3238425384636, 
    "title" : "i3jMH8CHPWY6Ru18KrmsDGdiyl2qDuFjxXD1M4yCzJHrOmSF8v", 
    "body_html" : "This is body", 
    "vendor" : NumberInt(1), 
    "__v" : NumberInt(0)
},
{
    "_id" : ObjectId("6128a0d9cf34c208c30e6805"), 
     "id" : 30336405569734,
},
{},
{},
{},
{}

API 是

http://localhost:3000/products.json?since_id=30336405569734&limit=10

【问题讨论】:

  • 您可以创建一个包含 10 个 id 的数组,从您拥有的那个开始。所以你得到var arr = [46,47,48, ...,55]; 并像这样使用它.find({ from_id: {$in: arr }})
  • 我收集了超过 75 条 lac 记录,不想进行数组处理迭代等等

标签: node.js mongodb mongoose nosql


【解决方案1】:

以 10ids 为例,我们想从 4 开始得到 4 个 ids

  • 过滤器ID>=4
  • 排序升序 id
  • 限制2

对于您想要读取查询字符串然后您想要的数据,id>=30336405569734limit 10 。(数字不是字符串)

Test code here

您可以在 mongoose 中使用聚合。

db.collection.aggregate([
  {
    "$match": {
      "id": {
        "$gte": 4    // "$gte": 30336405569734 (for your data)
      }
    }
  },
  {
    "$sort": {
      "id": 1
    }
  },
  {
    "$limit": 2    //  "$limit": 10 (for your data)
  }
])

或者在mongoose中写一个find,我不用mongoose但是我觉得会是这样的。

products_model.find({ id: { $gte: 30336405569734 } })
  .sort({id: 1})
  .limit(10)
  .then(products => {
    console.log(products)
  });

await products_model.find({ id: { $gte: 30336405569734 } })
  .sort({id: 1})
  .limit(10));

【讨论】:

  • 这段代码怎么样 return products_model.find({'id': since_id}).limit(limit).exec((err, since_product) => { if(err) { reject(err) } else { if(since_product.length >0) { return products_model.find({_id: {$gt: since_product[0]._id}}).limit(limit).exec((err, records) => { if (err) reject(err) else resolve([...since_product,...records]) }) } else { resolve({"message": "Product Not Found"}) } } })
  • 因为默认情况下我没有“_id”,所以我在 since_id 变量中有值,它将从集合中获取列名作为 id。和 id 可以有随机顺序的随机数
  • 如果你能给出一个数据的例子,你想得到什么结果,来查询你的数据,我不使用猫鼬,但你想要的查询似乎很简单。
  • 我希望更新有所帮助,我没有更改查询,只是将 _id 替换为 id,如果您不想聚合,我还尝试使用 mongoose find 编写它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多