MongoDB findOne() method returns only one document that satisfies the criteria entered. If the criteria entered matches for more than one document, the method returns only one document according to natural ordering, which reflects the order in which the documents are stored in the database.
MongoDB findOne()方法仅返回一个满足输入条件的文档。 如果输入的条件匹配多个文档,则该方法将根据自然顺序仅返回一个文档,这反映了文档在数据库中的存储顺序。
MongoDB findOne (MongoDB findOne)
MongoDB findOne() syntax is:
MongoDB findOne()语法为:
db.collection.findOne(<criteria>, <projection>)
db.collection.findOne(<criteria>, <projection>)
criteria – specifies the selection criteria entered.
标准 –指定输入的选择标准。
projection – specifies the list of fields to be displayed in the returned document.
投影 –指定要在返回的文档中显示的字段列表。
Few important points about MongoDB findOne:
关于MongoDB findOne的几点要点:
- The projection parameter accepts the boolean values of 1 or true , 0 or false. If the projection fields are not specified, all the fields will be retrieved. projection参数接受布尔值1或true,0或false。 如果未指定投影字段,则将检索所有字段。
- MongoDB findOne() always includes the _id field even if not specified explicitly in the projection parameter unless it is excluded. MongoDB findOne()始终包含_id字段,即使未在projection参数中明确指定,除非将其排除。
- MongoDB findOne() returns only a document but not a cursor. MongoDB findOne()仅返回文档,而不返回游标。
MongoDB findOne –空查询规范 (MongoDB findOne – Empty Query specification)
This operation returns a single document from the collection specified.
此操作从指定的集合中返回单个文档。
For example, db.car.findOne()
例如, db.car.findOne()
Output:
输出:
{
"_id" : 2,
"name" : "Polo", "color" : "White",
"cno" : "H411", "speed" : 45, "mfdcountry" : "Japan"
}
Only one record is retrieved from the car
collection. Note that “Polo” was inserted first into the database.
从car
收藏中仅检索到一条记录。 请注意,“ Polo”首先插入数据库。
MongoDB findOne –查询规范 (MongoDB findOne – Query specification)
This MongoDB findOne operation returns the first matching document from the specified collection along with the selection criteria entered.
此MongoDB findOne操作将返回指定集合中的第一个匹配文档以及输入的选择条件。
For example:
例如:
>db.car.findOne(
... {
... $or:[
... {name:"Zen"},
... {speed: {$gt:60}} ... ]
... }
... )
{
"_id" : ObjectId("546cb92393f464ed49d620db"),
"name" : "Zen",
"color" : "JetRed",
"cno" : "H671",
"speed" : 67,
"mfdcountry" : "Rome"
}
This operation searches for the car named “Zen” or for speed greater than 60 and retrieves the first document satisfying the criteria entered from the car collection.
此操作搜索名为“ Zen”的汽车或速度大于60的汽车,并检索满足从汽车收藏集中输入的条件的第一个文档。
MongoDB中的投影findOne() (Projection in MongoDB findOne())
The projection parameter is also applicable for MongoDB findOne method. Let’s look at some scenarios where we can use projection in findOne.
投影参数也适用于MongoDB findOne方法。 让我们看一些可以在findOne中使用投影的场景。
MongoDB findOne –指定要返回的字段 (MongoDB findOne – specify the fields to be returned)
This operation displays only the fields specified in the query.
此操作仅显示查询中指定的字段。
For example:
例如:
>db.car.findOne(
... { },
... {name:1,color:1}
... )
{ "_id" : 2, "name" : "Polo", "color" : "White" }
The first document from the Car collection with id, name and color fields are displayed.
将显示Car集合中具有ID,名称和颜色字段的第一个文档。
MongoDB findOne –返回除排除字段以外的所有字段 (MongoDB findOne – return all the fields except the excluded one)
This operation retrieves the first document excluding the fields specified in the selection criteria.
此操作将检索除选择标准中指定的字段以外的第一个文档。
For example;
例如;
>db.car.findOne(
... { name:"Volkswagen" },
... {_id:0, mfdcountry:0,cno:0 }
... )
{ "name" : "Volkswagen", "color" : "JetBlue", "speed" : 62 }
The car name with Volkswagen is retrieved excluding the id, mfdcountry and cno fields.
检索带有大众汽车的汽车名称,但不包括id,mfdcountry和cno字段。
MongoDB findOne结果文档 (MongoDB findOne result document)
Cursor methods will not work in this operation as the method returns only a single document. In order to print the individual field values from the document, we can use the below code.
游标方法将无法执行此操作,因为该方法仅返回单个文档。 为了打印文档中的各个字段值,我们可以使用以下代码。
>var car = db.car.findOne();
> if (car) {
... var carName = car.name;
... print (tojson(carName));
... }
"Polo"
This retrieves only the name of the car “Polo”.
这仅检索汽车“ Polo”的名称。
MongoDB findOne Java示例 (MongoDB findOne Java Example)
Below is the java program showing different options that we can use with MongoDB findOne().
下面的Java程序显示了我们可以与MongoDB findOne()一起使用的不同选项。
MongoDBFindOne.java
MongoDBFindOne.java
package com.journaldev.mongodb;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
public class MongoDBFindOne {
// method retrieves the first document without any criteria
public static void emptyFindOne() throws UnknownHostException {
// Get a new connection to the db assuming that it is running
MongoClient mongoClient = new MongoClient("localhost");
// use test as a datbase,use your database here
DB db = mongoClient.getDB("test");
// fetch the collection object ,car is used here,use your own
DBCollection coll = db.getCollection("car");
// invoking findOne() method
DBObject doc = coll.findOne();
// prints the resultant document
System.out.println(doc);
}
// method that retrieves the document based on the selection criteria
public static void querySpecification() throws UnknownHostException {
// getting a connection everytime is not needed (could be done once
// globally).
MongoClient mongoClient = new MongoClient("localhost");
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("car");
// query to filter the document based on name and speed values by
// creating new object
DBObject query = new BasicDBObject("name", "Zen").append("speed",
new BasicDBObject("$gt", 30));
// resultant document fetched by satisfying the criteria
DBObject d1 = coll.findOne(query);
// prints the document on console
System.out.println(d1);
}
public static void projectionFields() throws UnknownHostException {
MongoClient mongoClient = new MongoClient("localhost");
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("car");
// creates new db object
BasicDBObject b1 = new BasicDBObject();
// criteria to display only name and color fields in the resultant
// document
BasicDBObject fields = new BasicDBObject("name", 1).append("color", 1);
// method that retrieves the documents by accepting fields and object
// criteria
DBObject d1 = coll.findOne(b1, fields);
System.out.println(d1);
}
public static void excludeByfields() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB db = m1.getDB("test");
DBCollection col = db.getCollection("car");
// filter criteria for car name volkswagen
DBObject query = new BasicDBObject("name", "Volkswagen");
// excluding the fields mfdcountry,cno and id fields
BasicDBObject fields = new BasicDBObject("mfdcountry", 0).append("cno",
0).append("_id", 0);
DBObject d1 = col.findOne(query, fields);
System.out.println(d1);
}
public static void printDoc() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB db = m1.getDB("test");
DBCollection col = db.getCollection("car");
DBObject d1 = col.findOne();
// prints only the name of the car
System.out.println((d1.get("name")));
}
public static void main(String[] args) throws UnknownHostException {
// invoking all the methods from main
emptyFindOne();
querySpecification();
projectionFields();
excludeByfields();
printDoc();
}
}
Output of above program is:
上面程序的输出是:
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "speed" : 45.0 , "mfdcountry" : "Japan"}
{ "_id" : { "$oid" : "546cb92393f464ed49d620db"} , "name" : "Zen" , "color" : "JetRed" , "cno" : "H671" , "speed" : 67 , "mfdcountry" : "Rome"}
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White"}
{ "name" : "Volkswagen" , "color" : "JetBlue" , "speed" : 62}
Polo
That’s all for MongoDB findOne() method, we will look into more MongoDB options in coming posts.
这就是MongoDB findOne()方法的全部内容,我们将在以后的文章中探讨更多MongoDB选项。
Reference: Official Doc
参考: 官方文件
翻译自: https://www.journaldev.com/6197/mongodb-findone-example