要从MongoDB中查询并获取数组中的一项,您需要使用点表示法(dot notation)
假设我们有一个名为students
的集合,其中每个文档都包含一个名为grades
的数组,您可以使用以下查询来获取特定学生的第一个成绩:
db.students.find({ "_id": student_id }, { "grades.0": 1, "_id": 0 })
在这个示例中,student_id
是您要查询的学生的ID。grades.0
表示我们只想要数组grades
中的第一个元素。1
表示我们包含这个字段,而_id: 0
表示我们不包含默认返回的_id
字段。
如果您使用的是MongoDB驱动程序,例如Node.js的MongoDB驱动程序,查询可能如下所示:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("students");
const query = { "_id": student_id };
const projection = { "grades.0": 1, "_id": 0 };
collection.findOne(query, { projection }, (err, result) => {
if (err) throw err;
console.log(result.grades[0]); // 打印第一个成绩
client.close();
});
});
在这个Node.js示例中,我们使用findOne
方法来获取匹配查询条件的第一个文档,并使用projection
参数来指定我们只想要数组grades
中的第一个元素。然后,我们可以从结果中访问grades[0]
以获取第一个成绩。