如何在Node.js中从MongoDB查询指定时长内创建的文档?
Hey there! Let's walk through how to fetch documents from the last N minutes (like 10 or 20) in MongoDB using Node.js, with a focus on your specific time field formats.
Core Concept
The key idea is to calculate a time threshold (current time minus the number of minutes you want to look back), then query for documents where your time field is greater than or equal to this threshold. The implementation varies slightly depending on whether your time field is an ISODate or a string-formatted date.
1. Querying for the Last 20 Minutes (General Use Case)
This works for any valid date field (like your timeTwo). First, calculate the threshold:
const twentyMinutesAgo = new Date(Date.now() - 20 * 60 * 1000); // 20 mins converted to milliseconds
Then use this threshold in your find() query to get all documents where the time field falls within the last 20 minutes.
2. Handling Your Specific Time Fields
Let's break down queries for both your timeOne (string) and timeTwo (ISODate) fields, using a reusable Node.js function.
Case A: timeTwo (ISODate Format)
Since timeTwo is stored as MongoDB's native ISODate, we can directly compare it to our threshold without any conversion. This is the most efficient approach because MongoDB can use indexes on timeTwo to speed up the query.
Case B: timeOne (String Format: "MM-DD-YYYYTHH:mm:ss")
timeOne is a string, so we need to convert it to a date type first in the query. We'll use MongoDB's $dateFromString operator (inside $expr to allow field-based expressions) to parse the string into a date, then compare it to our threshold.
Full Node.js Function Example (Using Official MongoDB Driver)
const { MongoClient } = require('mongodb'); // Replace these with your actual MongoDB credentials const MONGODB_URI = 'mongodb://localhost:27017'; const DB_NAME = 'your-database-name'; const COLLECTION_NAME = 'your-collection-name'; async function getDocumentsFromLastNMinutes(minutes = 10) { let client; try { // Connect to MongoDB client = new MongoClient(MONGODB_URI); await client.connect(); const db = client.db(DB_NAME); const collection = db.collection(COLLECTION_NAME); // Calculate the threshold time: current time minus N minutes const threshold = new Date(Date.now() - minutes * 60 * 1000); // Query for documents with timeTwo in the last N minutes const recentTimeTwoDocs = await collection.find({ timeTwo: { $gte: threshold } }).toArray(); // Query for documents with timeOne (string) parsed to date in the last N minutes const recentTimeOneDocs = await collection.find({ $expr: { $gte: [ { $dateFromString: { dateString: "$timeOne", format: "%m-%d-%YT%H:%M:%S" // Exact match for your string format } }, threshold ] } }).toArray(); console.log(`Found ${recentTimeTwoDocs.length} docs using timeTwo`); console.log(`Found ${recentTimeOneDocs.length} docs using timeOne`); return { recentTimeTwoDocs, recentTimeOneDocs }; } catch (err) { console.error('Error fetching documents:', err); throw err; } finally { // Always close the connection if (client) await client.close(); } } // Usage: Fetch documents from the last 10 minutes getDocumentsFromLastNMinutes(10); // To fetch from last 20 minutes, call: // getDocumentsFromLastNMinutes(20);
Key Notes
- Indexing: For better performance, add an index on
timeTwousingdb.collection.createIndex({ timeTwo: 1 }). FortimeOne, you can't index the converted value directly—if you regularly query by this field, consider storing it as an ISODate instead of a string to enable indexing. - Format Accuracy: The
formatparameter in$dateFromStringmust exactly match yourtimeOnestring format. In your case,%m-%d-%YT%H:%M:%Scorresponds to "06-28-2019T22:34:01". - Mongoose Users: If you're using Mongoose, the query logic is identical—just replace the MongoDB driver calls with your Mongoose model's
find()method.
内容的提问来源于stack exchange,提问作者rviDesai

