You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js如何在MongoDB的最新若干文档中进行查询

Querying Within the Latest N Documents in MongoDB

Hey there! Let's fix up your code and cover the two common scenarios for querying the latest documents in MongoDB, based on your example data and code snippet.

First, note that your original code has a small issue: the .limit() method needs a numeric argument to specify how many "latest" documents you want to target (e.g., 100 for the newest 100 entries).

Scenario 1: Find "Felicity" in the latest N documents of the entire collection

If you want to first grab the newest N documents from the cansOne collection, then filter those to find entries where name is "Felicity", you'll need to use MongoDB's aggregation pipeline (since we need to limit the document set before filtering):

dbo.collection("cansOne").aggregate([
  // Step 1: Sort documents by _id descending (newest first, since ObjectId includes timestamp)
  { $sort: { _id: -1 } },
  // Step 2: Keep only the latest N documents (replace 100 with your desired number)
  { $limit: 100 },
  // Step 3: Filter the limited set to find entries with name "Felicity"
  { $match: { name: "Felicity" } }
]).exec(function(err, results) {
  if (err) {
    console.error("Query error:", err);
    return;
  }
  // Your custom logic here
  console.log("Matching results from latest 100 docs:", results);
});

Scenario 2: Find the latest N documents where name is "Felicity"

If you want all entries named "Felicity", then retrieve the newest N of those, you can use the standard find() chain (filter first, then sort and limit):

dbo.collection("cansOne")
  .find({ name: "Felicity" }) // First filter for "Felicity"
  .sort({ _id: -1 }) // Sort newest to oldest
  .limit(100) // Keep only the latest 100 matching docs
  .exec(function(err, results) {
    if (err) {
      console.error("Query error:", err);
      return;
    }
    // Your custom logic here
    console.log("Latest 100 'Felicity' entries:", results);
  });

Quick note on sorting by _id

MongoDB's ObjectId includes a timestamp as its first 4 bytes, so sorting by _id: -1 is equivalent to sorting by creation time from newest to oldest—perfect for grabbing the latest documents without needing a separate "createdAt" field!

内容的提问来源于stack exchange,提问作者Vipul Solanki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:58:04