[英]How do I return a document with filtered sub-documents using Mongo.Driver.Linq with the Mongo C# driver 2.3?
[英]How to insert document with empty key using Mongo C driver?
我在 C 中有這個程序( Mongo C 驅動程序文檔中的 hello world 示例略有變化:
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
// file insert.c
// compiled with: gcc -o insert insert.c $(pkg-config --libs --cflags libmongoc-1.0)
int main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "", "my_key_is_empty");
if (!mongoc_collection_insert_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
重要的聲明是這個,設置一個空的 BSON 密鑰(這有點奇怪但合法):
BSON_APPEND_UTF8 (doc, "", "my_key_is_empty");
如果我運行程序,我會收到此錯誤:
invalid document for insert: empty key
這有點令人驚訝,因為如果我嘗試對 Mongo shell 做同樣的事情,它工作正常:
> db.mycoll.insert({"": "my_key_is_empty"})
WriteResult({ "nInserted" : 1 })
> db.mycoll.find()
{ "_id" : ObjectId("60182cb49fb197394497431e"), "" : "my_key_is_empty" }
所以:
你能幫我解決這個問題嗎? 謝謝!
關於我的系統的一些附加信息:
它似乎是一個功能。
您可以使用BSON_VALIDATE_EMPTY_KEYS
libbson 選項來控制是否執行此驗證。
這個版本的程序解決了這個問題:
include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
// file insert.c
// compiled with: gcc -o insert insert.c $(pkg-config --libs --cflags libmongoc-1.0)
int main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "", "my_key_is_empty");
bson_t *opt = BCON_NEW("validate", BCON_BOOL(false));
if (!mongoc_collection_insert_one (
collection, doc, opt, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (doc);
bson_destroy (opt);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
重要的部分是關閉驗證:
bson_t *opt = BCON_NEW("validate", BCON_BOOL(false));
if (!mongoc_collection_insert_one (
collection, doc, opt, NULL, &error)) {
...
}
...
bson_destroy (opt);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.