Saturday, 3 December 2011

Simple mongodb equivalents

After making a noob error today, I realised that some of the documentation could use a boost.

By default mongo returns the entire document.



SELECT * FROM foo WHERE bar=69
db.foo.find({bar:69})

All fields for the matched document will be returned

And in java


DBObject query = new BasicDBObject();
query.put("bar", 69);
DBCursor cursor = collection.find(query);


To return only certain fields, you need to let mongo know which ones you want


SELECT meh,feh FROM foo WHERE bar=69
db.foo.find({bar:69}, {meh:1,feh:1})

The will only return the fields meh and feh from the matched document

And in Java

DBObject query = new BasicDBObject();
query.put("bar", 69);
DBObject fields = new BasicDBObject();
fields.put("meh", 1);
fields.put("feh", 1);
DBCursor cursor = collection.find(query, fields);


You can also say 'all fields except for...'


I'm not aware of an ANSI SQL equivalent
db.foo.find({bar:69}, {meh:0})


This will return all the fields in the matched document expect for meh

And in Java

DBObject query = new BasicDBObject();
query.put("bar", 69);
DBObject fields = new BasicDBObject();
fields.put("meh", 0);
DBCursor cursor = collection.find(query, fields);

No comments:

Post a Comment