mongodb find_MongoDB find()

mongodb find

There are two ways to find an item from the MongoDB database. One is through MongoDB find method and the other is through findOne method. Let’s go through find() method first from the shell and later through a Java program.

有两种方法可以从MongoDB数据库中查找项目。 一种是通过MongoDB find方法,另一种是通过findOne方法。 让我们首先从外壳中通过find()方法,然后再通过Java程序。

MongoDB find() (MongoDB find())

MongoDB find method fetches the document in a collection and returns the cursor for the documents matching the criteria requested by the user.

MongoDB的find方法获取集合中的文档,并返回与用户要求的条件相匹配的文档的游标。

The syntax for mongodb find() method is as follows db.collection.find(<criteria>,<projection>)
.

mongodb find()方法的语法如下db.collection.find(<criteria>,<projection>)

criteria: field specifies the selection criteria entered by the user.

条件 :字段指定用户输入的选择条件。

projection: specifies the fields returned using projection operators.

projection :指定使用投影运算符返回的字段。

Projection operators can be any of the following.

投影运算符可以是以下任意一种。

  1. $: first element that matches the condition.

    $:匹配条件的第一个元素。
  2. $elemMatch: first element that matches the criteria specified in elem condition.

    $ elemMatch:与elem条件中指定的条件匹配的第一个元素。
  3. $slice: limits the number of elements in an array.

    $ slice:限制数组中元素的数量。
  4. $meta: document score assigned during text operation. 
If the projection argument is specified then the cursor returns only projection field and _id field. The _id field can be excluded. By default the first 20 documents will be displayed. The syntax for projection parameter is 
{ field1: <boolean>, field2: <boolean> … }
The boolean values can be 0 or false to exclude the field and 1 or true to include the field. Let us now look at the various ways of putting this into use.

    $ meta:文本操作期间分配的文档分数。 如果指定了投影参数,则光标仅返回投影字段和_id字段。 _id字段可以排除。 默认情况下,将显示前20个文档。 投影参数的语法为{field1:<boolean>,field2:<boolean>…}布尔值可以为0或false来排除该字段,为1或true来包括该字段。 现在让我们看看使用它的各种方法。

MongoDB查找–查找集合中的所有文档 (MongoDB find – finding all the documents in the collection
)

This method returns all the documents present in the database of the specified collection.

此方法返回指定集合的​​数据库中存在的所有文档。

For example: db.car.find()

例如: db.car.find()

Output:

输出:

{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c7c7d6be0faf69ee36546"), "name" : "WagonR", "speed" : 5, "color" : "Blue" }
{ "_id" : ObjectId("546c9f347256eabc40c9da1c"), "cno" : "Silver", "color" : "Silver", "name" : "HondaCity", "speed" : 45 }
{ "_id" : ObjectId("546cb92393f464ed49d620db"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cb9c293f4d93688ebaff6"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

MongoDB查找–获取与给定查询条件匹配的文档 (MongoDB find – fetching the documents that match the given query criteria)

This fetches the documents that match the selection criteria specified by the user.

这将提取与用户指定的选择标准相匹配的文档。

For example: db.car.find( { speed: { $gt:50 } }) 
Fetches documents with speed greater than 50.

例如: db.car.find( { speed: { $gt:50 } })速度大于50的文档。

Output:

输出:

{ "_id" : ObjectId("546cb92393f464ed49d620db"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cb9c293f4d93688ebaff6"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

MongoDB查找–基于文档相等性进行获取 (MongoDB find – fetching based on equality of documents)

This mongodb find query fetches the document which satisfies the equality condition.

这个mongodb find查询获取满足相等条件的文件。


For example: db.car.find( { _id: 3} )

例如: db.car.find( { _id: 3} )

Output:

输出:

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

The document having the value of 3 as id is retrieved.

检索值为3作为id的文档。

MongoDB查找–使用多个匹配条件作为查询运算符来获取文档 (MongoDB find – fetching document using multiple matching criteria as Query operators)

This operation fetches the document using more than one value as criteria specified.

此操作使用多个值作为指定的标准来获取文档。


For example db.car.find(
{
_id:{ $in: [3,2]} }).

例如db.car.find( { _id:{ $in: [3,2]} })

Output:

输出:

{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

The documents having id of values 2 and 3 is fetched using the in operator.

使用in运算符可获取ID值为2和3的文档。

MongoDB查找–使用范围运算符获取文档 (MongoDB find – fetching the document using range operators
)

This find operation fetches the document having values within the range specified.

该查找操作将获取值在指定范围内的文档。

For example 
db.car.find( { speed: {$gt:40, $lt:65}})

例如db.car.find( { speed: {$gt:40, $lt:65}})

Output:

输出:

{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c9f347256eabc40c9da1c"), "cno" : "Silver", "color" : "Silver", "name" : "HondaCity", "speed" : 45 }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

The documents whose car’s speed greater than 40 but less than 65 is retrieved.

检索车速大于40但小于65的文档。

MongoDB找到投影 (MongoDB find projection)

MongoDB projections are nothing but the fields that we wish to display as a part of the output. There are multiple usages here too.

MongoDB投影不过是我们希望显示为输出一部分的字段。 这里也有多种用法。

mongoDB查找投影-指定字段 (mongoDB find projection – specifying the fields)

This operation displays the fields that are chosen using projection parameter.

此操作显示使用投影参数选择的字段。

For example:
 db.car.find( {speed: {$gt:60} },{name:1,speed:1})

例如: db.car.find( {speed: {$gt:60} },{name:1,speed:1})

Output:

输出:

{ "_id" : ObjectId("546cb92393f464ed49d620db"), "name" : "Zen", "speed" : 67 } { "_id" : ObjectId("546cb9c293f4d93688ebaff6"), "name" : "Zen", "speed" : 67 }
{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "speed" : 67 }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "speed" : 67 }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "speed" : 62 }

This operation finds all the documents in the car collection whose speed is greater than 50 and the fields name, speed and id are displayed as specified in the projection parameter.

此操作将查找汽车集合中所有速度大于50的文档,并按照投影参数中的指定显示字段名称,速度和id。

MongoDB查找投影–明确排除字段 (MongoDB find projection – exclude the fields explicitly)

This operation displays all the fields except the field specified in the projection parameter.

此操作将显示除projection参数中指定的字段以外的所有字段。

For Example 
db.car.find(
{speed:62}, {'mfdcountry':0,cno:0})

例如db.car.find( {speed:62}, {'mfdcountry':0,cno:0})

Output:

输出:

{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "speed" : 62 }

The operation displays all the fields of the collection car having speed of 62 except the fields mfdcountry and cno.

该操作将显示速度为62的收款车的所有字段,除了mfdcountry和cno字段。

MongoDB查找投影–明确排除_id字段 (MongoDB find projection – explicitly exclude the _id field)

This operation excludes the id field from the returned document.

此操作从返回的文档中排除id字段。

For example 
db.car.find( {speed: {$gt:65}},{_id:0})

例如db.car.find( {speed: {$gt:65}},{_id:0})

Output:

输出:

{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }

The car whose speed is greater than 65 is displayed without the _id field.

显示速度大于65的汽车时不显示_id字段。

迭代MongoDB返回的游标find (Iterating on the Cursors returned by MongoDB find)

As in other databases, a cursor is returned when there are multiple documents being returned. The returned cursor can be assigned to a variable using var keyword.

与在其他数据库中一样,当返回多个文档时,将返回一个游标。 可以使用var关键字将返回的光标分配给变量。

For example 
var carcursor = db.car.find();


例如var carcursor = db.car.find();

The next() method can be used by the cursor to access the subsequent documents from the cursor.

游标可以使用next()方法从游标访问后续文档。

>var carcursor = db.car.find();

>var myCar = carcursor.hasNext() ? carcursor.next():null;
>if (myCar) {
var carName = myCar.name; print (tojson(carName));}

Output: “Polo” (or it can be different, based on the first car returned in the next() call)

输出:“ Polo”(或者可以不同,具体取决于next()调用中返回的第一辆车)

carcursor.hasNext() returns true since there are many cars which causes carcursor.next() to be executed fetching the first document ( Polo record ) which gets assigned to myCar. myCar is checked for existence and the name is extracted as ‘Polo’.

carcursor.hasNext()返回true,因为有许多汽车导致carcursor.next()被执行,以获取分配给myCar的第一个文档(Polo记录)。 检查myCar是否存在,并将名称提取为“ Polo”。

MongoDB游标中的forEach方法用法查找查询 (forEach method usage in cursor of MongoDB find query)

The forEach method iterates over the cursor and retrieves all the documents.

forEach方法遍历游标并检索所有文档。

>var carCursor = db.car.find();
>carCursor.forEach(printjson);

In this example, carCursor iterates over all the items since we call forEach on it. The data is converted to json format for better understanding.

在此示例中,因为我们在其上调用forEach,所以carCursor会迭代所有项。 数据将转换为json格式,以便更好地理解。

mongoDB查找排序 (mongoDB find sort)

The sort() method is used to order the documents.

sort()方法用于对文档进行排序。

For example 
db.car.find().sort({name:1})

例如db.car.find().sort({name:1})

The sort method orders the car collection by name in ascending order.

sort方法按名称升序对汽车集合进行排序。

MongoDB查找–限制输出 (MongoDB find – limiting the output)

The limit() method is used to restrict the number of documents displayed to the user.

limit()方法用于限制显示给用户的文档数量。

For example 
db.car.find().limit(2);

例如db.car.find().limit(2) ;

Output:

输出:

{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

The first 2 records will only be displayed to the user as the limit is specified as 2.


前2条记录仅在限制为2时显示给用户。

MongoDB查找跳过方法 (MongoDB find skip method)

The skip() method specifies the starting point of the result set.

skip()方法指定结果集的起点。

For example 
db.car.find().skip(6)

例如db.car.find().skip(6)


Output:

输出:

{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

The first 6 records will be skipped and the remaining documents will be displayed because the starting point is set as 6

因为起始点设置为6,所以将跳过前6条记录,并显示其余文档。

MongoDB查找–链接多个方法 (MongoDB find – chaining multiple methods)

One or more methods can be combined as shown below.

可以如下组合一种或多种方法。

db.car.find().limit(2).sort({name:1})

db.car.find().limit(2).sort({name:1})


Output:

输出:

"_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c9f347256eabc40c9da1c"), "cno" : "Silver", "color" : "Silver", "name" : "HondaCity", "speed" : 45 }

mongoDB在数组中查找 (mongoDB find in array)

Lets create an array field regno and insert values into it.

让我们创建一个数组字段regno并将值插入其中。

> db.car.insert(
... [{_id:15, "regno":[5,10]},
... {_id:16, "regno":[11,20]},
... {_id:17, "regno":[21,30]}])
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 3,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
>


Now on performing db.car.find() operation, we can see the newly added regno array fields too.

现在执行db.car.find()操作时,我们也可以看到新添加的regno数组字段。

Execute the following query for fetching arrays:

执行以下查询以获取数组:

db.car.find( {regno: {$gt:5, $lt:20}})

db.car.find( {regno: {$gt:5, $lt:20}})


Output:

输出:

{ "_id" : 15, "regno" : [ 5, 10 ] }
{ "_id" : 16, "regno" : [ 11, 20 ] }

The above 2 records are fetched because 10 is greater than 5 and less than 20 and 11 is greater than 5 but less than 20.

由于10大于5且小于20且11大于5但小于20,因此获取了上述2条记录。

Let us query for finding a particular element in an array:

让我们查询在数组中查找特定元素:

db.car.find({regno:21})

db.car.find({regno:21})


Output: { “_id” : 17, “regno” : [ 21, 30 ] }
}

输出:{“ _id”:17,“ regno”:[21,30]}}

MongoDB查找Java示例 (MongoDB find java example)

Until now, we saw how to perform find operations using the Mongo console. In this section, we will see how to do the same using Java programs.

到目前为止,我们已经看到了如何使用Mongo控制台执行查找操作。 在本节中,我们将看到如何使用Java程序执行相同的操作。

package com.journaldev.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class MongoDBFindOperations {

	// method that retrieves all the documents present in the database without
	// any criteria
	public static void findAll() 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 find() method and storing the result in carCursor
		DBCursor carCursor = coll.find();

		// printing the cursor contents
		try {
			while (carCursor.hasNext()) {
				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();// close the cursor
		}
	}
	
	// method to retrieve documents based on the selection criteria
	public static void findBYCriteria() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// criteria specified as speed greater than 50
		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 50));
		// /result stored in cursor using find() method
		DBCursor carCursor1 = col.find(query);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void findByEquality() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// criteria with id 3 is specified
		DBObject query = new BasicDBObject("_id", 3);
		DBCursor c1 = col.find(query);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (c1.hasNext()) {
				System.out.println(c1.next());
			}
		} finally {
			c1.close();
		}
	}
	
	public static void findByQueryOperators() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// criteria with speed greater than 40 and less than 65
		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 40).append("$lt", 65));
		DBCursor carCursor1 = col.find(query);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void findByfields() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 60));
		// fields with name and speed field is specified and only these fields
		// are displayed
		BasicDBObject fields = new BasicDBObject("name", 1).append("speed", 1);
		DBCursor carCursor1 = col.find(query, fields);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void excludeByfields() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 65));
		// excluding mfdcountry and cno fields by setting to 0
		BasicDBObject fields = new BasicDBObject("mfdcountry", 0).append("cno",
				0);
		DBCursor carCursor1 = col.find(query, fields);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void excludeByIdfield() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 65)); // excluding id field by setting
												// to 0
		BasicDBObject fields = new BasicDBObject("_id", 0);
		DBCursor carCursor1 = col.find(query, fields);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}

	public static void sortMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		DBCursor carCursor = col.find();
		// sort the car collection in ascending order
		carCursor.sort(new BasicDBObject("name", 1));
		
		try {
			while (carCursor.hasNext()) {

				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void limitMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		// limits to only 2 records
		DBCursor carCursor = col.find().limit(2);
		
		try {
			while (carCursor.hasNext()) {

				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void skipMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		// skips the first 10 records
		DBCursor carCursor = col.find().skip(10);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor.hasNext()) {

				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void sortLimitMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		DBCursor carCursor = col.find();
		// combining sort and limit methods
		carCursor.sort(new BasicDBObject("name", 1)).limit(2);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor.hasNext()) {
				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void insertArray() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car"); // regno array is declared
		List<Integer> regno = new ArrayList<Integer>();
		// adding values to regno field
		regno.add(31);
		regno.add(41);
		regno.add(65);
		regno.add(75);
		// setting regno to new object b1
		BasicDBObject b1 = new BasicDBObject("regno", regno);
		// inserting b1 to collection col
		col.insert(b1);
		DBCursor c3 = col.find();
		try {
			while (c3.hasNext()) {
				System.out.println(c3.next());
			}
		} finally {
			c3.close();
		}
	}
	
	public static void queryArray() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// querying for array values greater than 31 and less than 65
		DBObject query = new BasicDBObject("regno",
				new BasicDBObject("$gt", 31).append("$lt", 65));
		DBCursor c1 = col.find(query);
		try {
			while (c1.hasNext()) {
				System.out.println(c1.next());
			}
		} finally {
			c1.close();
		}
	}
	
	public static void queryArrayElement() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// quering for regno 75
		DBObject query = new BasicDBObject("regno", 75);
		DBCursor c1 = col.find(query);
		
		try {
			while (c1.hasNext()) {
				System.out.println(c1.next());
			}
		} finally {
			c1.close();
		}
	}

}

You can use above program and check the output yourself. That’s all for MongoDB find, we will look into more of MongoDB methods in coming posts.

您可以使用上述程序并自己检查输出。 这就是MongoDB找到的全部内容,我们将在以后的文章中研究更多MongoDB方法。

Reference: Official Doc

参考: 官方文件

翻译自: https://www.journaldev.com/6178/mongodb-find

mongodb find

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值