检索MongoDB集合中的第一个文档?
要检索集合中的第一个文档,可以使用findOne()。以下是语法
var anyVariableName=db.yourCollectionName.findOne(); //要在MongoDB控制台上打印结果,请写入变量名称 yourVariableName
首先让我们创建一个包含文档的集合
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Robert","ClientAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2325966324ffac2a7dc6d")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Chris","ClientAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2326266324ffac2a7dc6e")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Larry","ClientAge":29});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2326a66324ffac2a7dc6f")
}
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"David","ClientAge":39});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2327566324ffac2a7dc70")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.retrieveFirstDocumentDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5ca2325966324ffac2a7dc6d"),
"ClientName" : "Robert",
"ClientAge" : 23
}
{
"_id" : ObjectId("5ca2326266324ffac2a7dc6e"),
"ClientName" : "Chris",
"ClientAge" : 26
}
{
"_id" : ObjectId("5ca2326a66324ffac2a7dc6f"),
"ClientName" : "Larry",
"ClientAge" : 29
}
{
"_id" : ObjectId("5ca2327566324ffac2a7dc70"),
"ClientName" : "David",
"ClientAge" : 39
}以下是检索集合中第一个文档的查询
> var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne(); > firstDocumentOnly;
这将产生以下输出
{
"_id" : ObjectId("5ca2325966324ffac2a7dc6d"),
"ClientName" : "Robert",
"ClientAge" : 23
}热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短