MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

L'ordine è importante in bson_iter_find nel driver mongo c

per rispondere direttamente alla tua domanda, dovresti chiamare bson_iter_init (http://api.mongodb. org/libbson/current/bson_iter_init.html ) per ogni singola "nuova" query che stai facendo sui dati.

Presumibilmente hai una singola chiamata bson_iter_init su un oggetto bson_t. Te ne serve solo un altro.

   bson_iter_t iterator1;
   bson_iter_t iterator2;

   if (bson_iter_init (&iterator1, doc) &&
       bson_iter_find (&iterator1, "fieldA") ) {
       //Do something with fieldA
    }

   if (bson_iter_init (&iterator2, doc) &&
       bson_iter_find (&iterator2, "fieldB") ) {
       //Do something with fieldB
    }
    bson_free(doc); //DONT FORGET TO DESTROY THE BSON_T object at the end.

oppure, usa semplicemente il comando combinato bson_iter_init_find (http://api.mongodb.org/ libbson/current/bson_iter_init_find.html ) se non vuoi occuparti degli interni.

   bson_iter_t iterator1;
   bson_iter_t iterator2;

   if (bson_iter_init_find (&iterator1, doc, "fieldA") ) {
       //Do something with fieldA
    }

   if (bson_iter_init_find (&iterator2, doc,"fieldB") ) {
       //Do something with fieldB
    }
    bson_free(doc); //DONT FORGET TO DESTROY THE BSON_T object at the end.

Se sei interessato al perché, lavoro su bsonsearch (https://github.com/bauman/bsonsearch ) libreria e hanno problemi simili.

Sii molto cauto su come gestisci i puntatori. Quasi tutto ciò che è nascosto in libbson sta manipolando i puntatori a un'area della memoria.

Il motivo per cui l'ordine conta è perché hai inizializzato una volta, quando hai chiamato iter_find, libbson cercherà oltre B per individuare A . La successiva chiamata per trovare B cercherebbe la fine del buffer e la mancherebbe. Eviti questo problema reinizializzando l'iteratore alla posizione 0 e avviando la ricerca da lì.

A meno che tu non sappia esattamente cosa stai facendo e desideri ottimizzare le ricerche intorno al buffer, probabilmente è meglio reinizializzare l'iteratore per ogni ricerca.