2

I have a simple query that worked on mongodb shell:

db.collection.find({"date": {$lt: ISODate("2015-11-03T00:00:00Z")} })

very simple, just trying to find any record that has date before 2015-11-03. Now i want to translate to similar code in mongoc driver, i have following code that doesn't work:

query = BCON_NEW (
   "date", "{", "$lt", "2015-11-03T00:00:00Z", "}", "}");    
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

anyone knows the correct way to write in mongoc? I have looked through mongoc.org, no related example there.

4

1 回答 1

3

BCON 非常敏感,但是一旦你掌握了它,它就非常有用

首先,您需要将 BCON 类型应用于不是键的任何内容并仔细计算您的大括号。每个左大括号都需要一个右大括号。BCON_NEW 本身将处理文档中的第一个和最后一个大括号。

query = BCON_NEW ("date", "{", "$lt", "2015-11-03T00:00:00Z", "}", "}"); 
                    ^             ^              ^                  ^
                    |             |              |                  |
keys ------------------------------              |                  |
value --------------------------------------------                  |
brace that shouldn't exist ------------------------------------------

此页面将告诉您可能希望为您的价值选择的透视类型

https://github.com/mongodb/libbson/blob/master/src/bson/bcon.c#L214-L292

您的集合说它包含一个 ISODate,因此您将需要 BCON_DATE_TIME 类型。

切换类型并去掉额外的尾随右括号,您的查询可能需要看起来像这样。

query = BCON_NEW ("date", "{", "$lt", BCON_DATE_TIME("2015-11-03T00:00:00Z"), "}");
于 2017-04-03T14:33:33.397 回答