A computer engineer poking at your cerebral cortex.

Mongodb C++ finding 1 value with BSON filter

I spent over 8 hours debugging this code and finally got some help on the mongodb IRC chat room. Hacking through this code was a nightmare and hopefully posting it here will alleviate many headaches for all. The documentation is so lacking sometimes but I guess that is why we have blogs like this!

So I want to get the last value inserted based on a filter(hostName) and the special _id field built into mongodb. This is how I did it:

So I wrote this:

void Database::getLastRecord(string hostName)
{
	//default variables
	string lastLine;
	BSONObjBuilder b;
 
	//build your BSON object filter:
	b.append("hostname", hostName);
	BSONObj p = b.obj();
 
	//execute your query
	mongo::BSONObj last_element = mongo.findOne("logs.ip",
			mongo::Query(p).sort("_id", -1));
 
	//now make sure your BSON object isn't empty
	//Also tell the BSON object which value you actually want with .getFiled() you can also use .toString() for the whole BSON object
	if (!last_element.isEmpty())
	{
		cout << last_element.getField("linenum") << endl;
		cout << last_element.toString() << endl;
	}
}