MongoDB distinct查询

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

MongoDB distinct方法为指定为输入参数的字段返回一组离散值。
Mongo distinct方法返回离散值数组。

MongoDB distinct

MongoDB与众不同的方法的语法是

db.collection.distinct(field, query)

field:要返回其离散值的字符串类型。

查询:指定要从中检索离散值的文档。

让我们看看使用mongo shell选择不同值的示例。

>db.car.distinct('speed')
[ 65, 55, 52, 45 ]

在mongo上,不同示例为car集合中的速度字段选择不同值的数组。
注意,查询参数是可选的。
现在,让我们看一下示例,在该示例中,我们将传递不同的查询参数以选择与查询条件匹配的不同值。

> db.car.distinct('name',{speed:{$gt:50}})
[
	"WagonR",
	"Xylo",
	"Alto800",
	"Astar",
	"Suzuki S-4",
	"Santro-Xing",
	"Palio",
	"Micra"
]
>

在MongoDB上方,不同的查询操作会在car集合中找到速度大于50的汽车的名称。

MongoDB distinct 查询 Java程序

考虑以下Java程序对car集合执行不同的操作,该集合为用户指定的字段打印一组离散值。

MongoDBDistinct.java

package com.theitroad.mongodb;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoDBDistinct {

	   public static void distinct() throws UnknownHostException{
	        
	        //Get a new connection to the db assuming that it is running 
	        MongoClient m1 = new MongoClient();
	        
	        //use test as a database,use your database here
	        DB db = m1.getDB("theitroad");
	        
	         //fetch the collection object ,car is used here,use your own 
	        DBCollection coll = db.getCollection("car");
	        
	        //call distinct method and store the result in list l1
	        List cl1= coll.distinct("speed");
	        
	        //iterate through the list and print the elements
	        for(int i=0;i<cl1.size();i++){
	            System.out.println(cl1.get(i));
	        }
	        
	        
	        
	        
	    }
	    
	    public static void distinctquery() throws UnknownHostException{
	       
	        MongoClient m1 = new MongoClient();
	        
	        DB db = m1.getDB("theitroad");
	        
	        DBCollection coll = db.getCollection("car");
	        
	        //condition to fetch the car document whose speed is greater than 50
	        DBObject o1 = new BasicDBObject("speed",new BasicDBObject("$gt",50));
	        
	        //call distinct method by passing the field name and object o1
	        List l1= coll.distinct("name", o1);
	        
	        System.out.println("-----------------------");
	        
	        for(int i=0;i<l1.size();i++){
	            
	           
	            System.out.println(l1.get(i));
	                    
	        }
	    }
	    public static void main(String[] args) throws UnknownHostException{
	        
	       //invoke all the methods to perform distinct operation	
	        distinct();
	        distinctquery();
	    }

}

上述MongoDB独特的Java程序的输出为:

65.0
55.0
52.0
45.0
----------------------
Audi
Swift
Maruthi800
Polo
Volkswagen
Santro
Zen
Ritz
Versa
Innova