MongoDB find()

时间:2020-02-23 14:40:50  来源:igfitidea点击:

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

MongoDB find()

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

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

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

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

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

  • $:匹配条件的第一个元素。

  • $elemMatch:与elem条件中指定的条件匹配的第一个元素。

  • $slice:限制数组中元素的数量。

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

MongoDB查找–查找集合中的所有文档

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

例如:db.car.find()

输出:

{ "_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查找–获取与给定查询条件匹配的文档

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

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

输出:

{ "_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查询获取满足相等条件的文件。

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

输出:

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

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

MongoDB查找–使用多个匹配条件作为查询运算符来获取文档

此操作使用多个值作为指定条件来获取文档。

例如`db.car.find({_ id:{$in:[3,2]}}))。

输出:

{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

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

MongoDB查找–使用范围运算符获取文档

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

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

输出:

{ "_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" }

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

MongoDB找到投影

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

mongoDB查找投影-指定字段

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

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

输出:

{ "_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 }

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

MongoDB查找投影–明确排除字段

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

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

输出:

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

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

MongoDB查找投影–明确排除_id字段

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

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

输出:

{ "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" }

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

迭代MongoDB返回的游标find

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

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

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

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

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

由于有许多汽车会导致执行carcursor.next()来获取分配给myCar的第一个文档(Polo记录),因此carcursor.hasNext()返回true。
检查myCar是否存在,并将其提取为" Polo"。

MongoDB游标中的forEach方法用法查找查询

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

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

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

mongoDB查找排序

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

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

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

MongoDB查找–限制输出

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

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

输出:

{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

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

MongoDB查找跳过方法

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

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

输出:

{ "_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" }

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

MongoDB查找–链接多个方法

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

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

输出:

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

mongoDB在数组中查找

让我们创建一个数组字段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" : [ ]
})
>

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

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

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

输出:

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

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

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

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

MongoDB查找-Java示例

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

package com.theitroad.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();
		}
	}

}