本文共 2914 字,大约阅读时间需要 9 分钟。
MongoDB distinct method returns a set of discrete values for the field specified as the input argument. Mongo distinct method returns an array of discrete values.
MongoDB独立方法为指定为输入参数的字段返回一组离散值。 Mongo独特方法返回离散值数组。
MongoDB与众不同的方法的语法是
db.collection.distinct(field, query)
field: A string type for which the discrete values are to be returned.
field :要返回其离散值的字符串类型。
query: Specifies the document from which discrete values are to be retrieved.
query :指定要从中检索离散值的文档。
Let’s see into the examples of select distinct values using mongo shell.
让我们看看使用mongo shell选择不同值的示例。
>db.car.distinct('speed')[ 65, 55, 52, 45 ]
Above mongo distinct example selects an array of distinct values for speed field in the car collection. Notice that query parameter is optional. Now let’s look at the example where we will pass distinct query parameter to select distinct values that matches the query criteria.
上面的mongo独特示例为car集合中的速度字段选择了一组独特的值。 注意,查询参数是可选的。 现在,让我们看一下示例,在该示例中,我们将传递不同的查询参数以选择与查询条件匹配的不同值。
> db.car.distinct('name',{speed:{$gt:50}})[ "WagonR", "Xylo", "Alto800", "Astar", "Suzuki S-4", "Santro-Xing", "Palio", "Micra"]>
Above MongoDB distinct query operation find the names of the car whose speed is greater than 50 in the car collection.
在MongoDB上方,不同的查询操作会在car集合中找到速度大于50的汽车的名称。
Consider the following java program to perform distinct operation on the car collection which prints a set of discrete values for the fields specified by the user.
考虑以下Java程序对car集合执行不同的操作,该集合为用户指定的字段打印一组离散值。
MongoDBDistinct.java
MongoDBDistinct.java
package com.journaldev.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("journaldev"); //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
Output of the above MongoDB distinct java program is:
以上MongoDB独特的Java程序的输出为:
65.055.052.045.0-----------------------AudiSwiftMaruthi800PoloVolkswagenSantroZenRitzVersaInnova
That’s all for MongoDB distinct examples. This is very helpful when you want to select distinct fields from a collection based on a certain criteria.
这就是MongoDB不同示例的全部内容。 当您要基于特定条件从集合中选择不同的字段时,这将非常有用。
翻译自:
转载地址:http://sjlzd.baihongyu.com/