Example usage for com.mongodb DBCollection getIndexInfo

List of usage examples for com.mongodb DBCollection getIndexInfo

Introduction

In this page you can find the example usage for com.mongodb DBCollection getIndexInfo.

Prototype

public List<DBObject> getIndexInfo() 

Source Link

Document

Return a list of the indexes for this collection.

Usage

From source file:org.springframework.data.mongodb.core.DefaultIndexOperations.java

License:Apache License

public List<IndexInfo> getIndexInfo() {

    return mongoOperations.execute(collectionName, new CollectionCallback<List<IndexInfo>>() {
        public List<IndexInfo> doInCollection(DBCollection collection)
                throws MongoException, DataAccessException {
            List<DBObject> dbObjectList = collection.getIndexInfo();
            return getIndexData(dbObjectList);
        }/*from w  w w  .  jav a  2s.  co m*/

        private List<IndexInfo> getIndexData(List<DBObject> dbObjectList) {

            List<IndexInfo> indexInfoList = new ArrayList<IndexInfo>();

            for (DBObject ix : dbObjectList) {

                DBObject keyDbObject = (DBObject) ix.get("key");
                int numberOfElements = keyDbObject.keySet().size();

                List<IndexField> indexFields = new ArrayList<IndexField>(numberOfElements);

                for (String key : keyDbObject.keySet()) {

                    Object value = keyDbObject.get(key);

                    if (TWO_D_IDENTIFIERS.contains(value)) {
                        indexFields.add(IndexField.geo(key));
                    } else if ("text".equals(value)) {

                        DBObject weights = (DBObject) ix.get("weights");
                        for (String fieldName : weights.keySet()) {
                            indexFields.add(IndexField.text(fieldName,
                                    Float.valueOf(weights.get(fieldName).toString())));
                        }

                    } else {

                        Double keyValue = new Double(value.toString());

                        if (ONE.equals(keyValue)) {
                            indexFields.add(IndexField.create(key, ASC));
                        } else if (MINUS_ONE.equals(keyValue)) {
                            indexFields.add(IndexField.create(key, DESC));
                        }
                    }
                }

                String name = ix.get("name").toString();

                boolean unique = ix.containsField("unique") ? (Boolean) ix.get("unique") : false;
                boolean dropDuplicates = ix.containsField("dropDups") ? (Boolean) ix.get("dropDups") : false;
                boolean sparse = ix.containsField("sparse") ? (Boolean) ix.get("sparse") : false;
                String language = ix.containsField("default_language") ? (String) ix.get("default_language")
                        : "";
                indexInfoList.add(new IndexInfo(indexFields, name, unique, dropDuplicates, sparse, language));
            }

            return indexInfoList;
        }
    });
}

From source file:parlare.application.server.model.Database.java

private String doClientMongo() {

    String print = "";

    System.out.println("User:" + user + " Source:" + source + " Password:" + password);

    try {//from ww  w.jav  a2 s .  c  om

        // connect to the local database server
        MongoClient mongoClient = new MongoClient(new ServerAddress(server),
                Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())),
                new MongoClientOptions.Builder().build());

        // get handle to "mydb"
        DB db = mongoClient.getDB("html5apps");

        // Authenticate - optional
        // boolean auth = db.authenticate("foo", "bar");

        // get a list of the collections in this database and print them out
        Set<String> collectionNames = db.getCollectionNames();
        for (String s : collectionNames) {

            System.out.println(s);
        }

        // get a collection object to work with
        DBCollection testCollection = db.getCollection("testCollection");

        // drop all the data in it
        testCollection.drop();

        // make a document and insert it
        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new BasicDBObject("x", 203).append("y", 102));

        testCollection.insert(doc);

        // get it (since it's the only one in there since we dropped the rest earlier on)
        DBObject myDoc = testCollection.findOne();
        System.out.println(myDoc);

        // now, lets add lots of little documents to the collection so we can explore queries and cursors
        for (int i = 0; i < 100; i++) {
            testCollection.insert(new BasicDBObject().append("i", i));
        }
        System.out.println("total # of documents after inserting 100 small ones (should be 101) "
                + testCollection.getCount());

        //  lets get all the documents in the collection and print them out
        DBCursor cursor = testCollection.find();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a query to get 1 document out
        BasicDBObject query = new BasicDBObject("i", 71);
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a range query to get a larger subset
        query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println("Cursor: " + cursor.next());
            }
        } finally {
            cursor.close();
        }

        // range query with multiple constraints
        query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // create an index on the "i" field
        testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

        //  list the indexes on the collection
        List<DBObject> list = testCollection.getIndexInfo();
        for (DBObject o : list) {
            System.out.println(o);
        }

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        // see if any previous operation had an error
        System.out.println("Previous error : " + db.getPreviousError());

        // force an error
        db.forceError();

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        db.resetError();

        // release resources
        mongoClient.close();

    } catch (UnknownHostException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

    return print;

}

From source file:teste.mongo.example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    /*//www.  ja  v  a 2  s. co m
    // Authenticate - optional
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
    MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
    */

    System.out.println("##### DataBaseInitial");
    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // get a db
    DB db = mongoClient.getDB("mydb");

    System.out.println("##### With new DataBase MYDB");
    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    mongoClient.dropDatabase("mydb");

    System.out.println("##### DataBase drop MYDB");
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // create a collection
    db = mongoClient.getDB("mydb");
    db.createCollection("testCollection", new BasicDBObject("capped", true).append("size", 1048576));

    System.out.println("##### ListAllCollection MYDB");
    // List all collections
    for (String s : db.getCollectionNames()) {
        System.out.println(s);
    }

    // Dropping a collection
    DBCollection testCollection = db.getCollection("testCollection");
    testCollection.drop();
    System.out.println("##### ListAllCollection MYDB - Drop testCollection");
    System.out.println(db.getCollectionNames());

    /* Indexes */
    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1));

    // Geospatial query
    coll.createIndex(new BasicDBObject("loc", "2dsphere"));

    BasicDBList coordinates = new BasicDBList();
    coordinates.put(0, -73.97);
    coordinates.put(1, 40.77);
    coll.insert(new BasicDBObject("name", "Central Park")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Parks"));

    coordinates.put(0, -73.88);
    coordinates.put(1, 40.78);
    coll.insert(new BasicDBObject("name", "La Guardia Airport")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Airport"));

    // Find whats within 500m of my location
    BasicDBList myLocation = new BasicDBList();
    myLocation.put(0, -73.965);
    myLocation.put(1, 40.769);
    DBObject myDoc = coll.findOne(new BasicDBObject("loc", new BasicDBObject("$near",
            new BasicDBObject("$geometry", new BasicDBObject("type", "Point").append("coordinates", myLocation))
                    .append("$maxDistance", 500))));
    System.out.println(myDoc.get("name"));

    // create a text index on the "content" field
    coll.createIndex(new BasicDBObject("content", "text"));

    coll.insert(new BasicDBObject("_id", 0).append("content", "textual content"));
    coll.insert(new BasicDBObject("_id", 1).append("content", "additional content"));
    coll.insert(new BasicDBObject("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    BasicDBObject search = new BasicDBObject("$search", "textual content -irrelevant");
    BasicDBObject textSearch = new BasicDBObject("$text", search);
    int matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new BasicDBObject("$text", search.append("$language", "english"));
    matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    BasicDBObject projection = new BasicDBObject("score", new BasicDBObject("$meta", "textScore"));
    myDoc = coll.findOne(textSearch, projection);
    System.out.println("Highest scoring document: " + myDoc);

    // list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // clean up
    mongoClient.dropDatabase("mydb");
    mongoClient.close();
}

From source file:tour.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*from   w  ww  .j  a v a  2 s .co  m*/
@SuppressWarnings("deprecation")
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to the "mydb" database
    DB db = mongoClient.getDB("mydb");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a handle to the "test" collection
    DBCollection collection = db.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    collection.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = collection.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<DBObject> documents = new ArrayList<DBObject>();
    for (int i = 0; i < 100; i++) {
        documents.add(new BasicDBObject().append("i", i));
    }
    collection.insert(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.getCount());

    // lets get all the documents in the collection and print them out
    DBCursor cursor = collection.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a query to get 1 document out
    cursor = collection.find(new BasicDBObject("i", 71));

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a range query to get a larger subset
    cursor = collection.find(new BasicDBObject("i", new BasicDBObject("$gt", 50)));

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)));

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // create an ascending index on the "i" field
    collection.createIndex(new BasicDBObject("i", 1));

    // list the indexes on the collection
    List<DBObject> list = collection.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // release resources
    mongoClient.close();
}