Get data between two dates mongoDb using C Driver Get data between two dates mongoDb using C Driver mongodb mongodb

Get data between two dates mongoDb using C Driver


Probably need an $and query. If BCON is available, use it.

#include <bson.h>#include <bcon.h>...    query = BCON_NEW("$and","[",                     "{", "timestamp", "{", "$gte", BCON_INT64(1460703944149), "}", "}",                     "{", "timestamp", "{", "$lt", BCON_INT64(1460703944683), "}", "}","]");...


I know this is an old question, but I wanted to just chime in with some points that could be useful.

First off, I think this would probably be easier to visualize with BCON (basic documentation here), but I believe the specific error referenced in the question is due to the presence of the extra comma inside the timestamp document (this one: {"$gte":1460703944149, "$lt":1460703944683 }. That comma is fine in JSON, but it makes the macro fail because it thinks you're now sending in the next argument. You could overcome that with the technique described here, but I believe you'll still have issues once that's resolved, because it looks like the BSON_APPEND_UTF8 signature expects a pointer to your document, then the key, then the UTF8 string value. From the tutorial:

This example adds a call to BSON_APPEND_UTF8() to look for all documents matching {"hello" : "world"}...

BSON_APPEND_UTF8 (query, "hello", "world");

But, here, you'd want to set the timestamp field to a document, not a UTF8 value. The document that you would supply would have a $gte field and a $lt field set to your date/time bounds. You'll also need to add your userId field to your query document, and then you should have the finished query that you can send in.

With the bson_append_<insert datatype here> methods, I believe you could do something like the following to accomplish this (I have not tested this code, but I think it should be fairly close):

bson_t *query;bson_t timestampDoc;query = bson_new();BSON_APPEND_DOCUMENT_BEGIN(query, "timestamp", &timestampDoc);bson_append_date_time(&timestampDoc, "$gte", -1, 1460703944149);bson_append_date_time(&timestampDoc, "$lt", -1, 1460703944683);bson_append_document_end(query, &timestampDoc);BSON_APPEND_UTF8(query, "userId", "manaf");

or, using BCON:

bson_t *query;query = BCON_NEW("timestamp",     "{",         "$gte", BCON_INT64(1460703944149),          "$lt", BCON_INT64(1460703944683),     "}",    "userId", BCON_UTF8("manaf"),);


Can you change the arguments of macro BSON_APPEND_UTF8 look like this

BSON_APPEND_UTF8 (query, "\"timestamp\": {\"$gte\":1460703944149, \"$lt\":1460703944683 }","\"userid\": \"manaf\"");