MongoDB usage notes (2)

Continuing prior notes from here.

Drop a database:

use databasename
db.dropDatabase()

List distinct property values across all docs:

db.collectionname.distict("propertyname")

Remove docs in a collection – param is a doc query. If empty doc, removes all docs:

db.collectionname.remove({})

Date range query using $gt and $lt for a range:

db.collectionname.find({ "timestamp" : { "$gte" : ISODate("2014-07-08T19:50"), "$lt" : ISODate("2014-07-08T19:52")  } })

[in progress]

MongoDB Java Driver notes

A few notes on using the MongoDB Java Driver API:

Getting a connection:

MongoClient client = new MongoClient("localhost", 27017);
DB db = client.getDB("test");

Get a collection from connected db:

DBCollection collection = db.getCollection("example");

 

Find all docs in collection and iterate through results:

DBCursor c = collection.find();
try {
   while(c.hasNext()) {
       System.out.println(c.next());
   }
} finally {
   c.close();
}

 

Simple findOne query, matching a doc with properyname = value:

DBObject result = collection.findOne(new BasicDBObject("propertyname", "value"));

 

Find all, sort on property ‘example’ ascending (1=asc, -1=desc), and limit to 10 results:

DBCursor c = collection.find()
    .sort(new BasicDBObject("example", 1))
    .limit(10);

 

Serialize results of a cursor to JSON (tip from here):

JSON json = new JSON();
String jsonString = json.serialize(c);

WildFly 8.2 WELD-001408 Unsatisfied Dependencies error

If you see an error like this:

WELD-001408: Unsatisfied dependencies for type [typename] with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject [propertyname]

… then you’re probably missing a default beans.xml file to initialize CDI in the container. The file doesn’t need to contain anything else than this:

<?xml version="1.0"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd" />

and drop it in /META-INF/ or /WEB-INF/

More info here and here.

MongoDB install on a Mac

By default MongoDB uses /data/db as it’s location for databases. You need to create this dir and then chown it to the user running mongod. For example:

sudo chown username /data/db

More info here.