面试题答案
一键面试在Python中使用pymongo
库来实现上述需求,示例代码如下:
import pymongo
# 连接MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["your_database"]
users_collection = db["users"]
# 使用游标遍历集合,限制每次返回10个文档
cursor = users_collection.find().limit(10)
for user in cursor:
print(user.get("name"))
在上述代码中,find()
方法返回一个游标对象,通过limit(10)
方法可以限制每次返回的文档数量为10个。然后使用for
循环遍历游标对象,输出每个用户的姓名。
如果是在JavaScript中使用mongodb
驱动,代码如下:
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function findUsers() {
try {
await client.connect();
const db = client.db("your_database");
const usersCollection = db.collection("users");
// 使用游标遍历集合,限制每次返回10个文档
const cursor = usersCollection.find().limit(10);
await cursor.forEach(user => {
console.log(user.name);
});
} finally {
await client.close();
}
}
findUsers();
在这段JavaScript代码中,同样使用find().limit(10)
来实现限制每次返回10个文档,并通过forEach
方法遍历游标输出用户姓名。