11

I want to create compound index on Age and Name in MongoDB through Java driver and here is my syntax:

coll.ensureIndex(new BasicDBObject("Age", 1),new BasicDBObject("Name", -1));
List <DBObject> list = coll.getIndexInfo();

  for (DBObject o : list) {
       System.out.println(o);
    }

but it create only 1 index not compund index and give me result this:

{ "v" : 1 , "key" : { "_id" : 1} ,"ns" :"EmployeeData.EmpPersonalData", "name":"_id_"}
{ "v" : 1 , "key" : { "Age" : 1} , "ns" : "EmployeeData.EmpPersonalData" , "name" : "Age_1" , "Name" : -1}

So how can compund index on collection can be created through java driver?

4

3 回答 3

27

如果您查看您的代码,您实际上已经调用ensureIndex了两个参数。你的第一个参数是键,你的第二个参数变成了一些额外的字段:Name: -1.

您要传入的第一个参数是 this object {"Age":1, "Name":-1}。你实际通过的是{"Age":1}, {"Name":-1}.

所以你想做这样的事情:

BasicDBObject obj = new BasicDBObject();
obj.put("Age", 1);
obj.put("Name", -1);
coll.ensureIndex(obj);

请注意,将使用默认名称创建索引。要提供特定名称,请执行以下操作:

coll.ensureIndex(obj, "MyName");
于 2012-07-15T04:16:49.967 回答
5

你可以根据官方文档试试这个。

import org.bson.Document;
db.getCollection("restaurants").createIndex(new Document("cuisine", 1).append("address.zipcode", -1));

官方 Mongo DB 驱动程序 Java 文档

于 2015-08-27T09:46:58.800 回答
2

一种更现代且可能更流畅的方法可能是:

import com.mongodb.client.model.Indexes;

collection
    .createIndex(
        Indexes.compoundIndex(
            Indexes.ascending("Age"),
            Indexes.descending("Name")
        )
    );

在手册中找到。为清晰起见格式化;根据自己的喜好后期格式。

于 2020-01-05T23:23:38.020 回答