Domanda

Utilizzando MongoDB C # conducente ( http://github.com/samus/mongodb-csharp), sembra che io sono in grado di ottenere i dati da ObjectId. Sotto il comando che sto usando:

var spec = new Document { { "_id", id } };
var doc = mc.FindOne(spec);

Inoltre ho provato questo:

var spec = new Document { { "_id", "ObjectId(\"" + id + "\")" } };
var doc = mc.FindOne(spec);

Sia niente ritorno. Nel frattempo, se interrogo dalla console mongo, restituisce il risultato atteso.

La mia domanda è, non che il driver in realtà supporta la ricerca per ObjectId?

Grazie ..

È stato utile?

Soluzione

Non supporta il recupero per ID oggetto. La variabile id dovrebbe essere un OID. È il tipo corretto?

Ecco un programma completo che sarà

  • Connetti a Mongo
  • Inserisci un documento
  • Scarica il documento indietro con il suo ID
  • Stampa i dettagli del documento.

// Connect to Mongo
Mongo db = new Mongo();
db.Connect();

// Insert a test document
var insertDoc = new Document { { "name", "my document" } };
db["database"]["collection"].Insert(insertDoc);

// Extract the ID from the inserted document, stripping the enclosing quotes
string idString = insertDoc["_id"].ToString().Replace("\"", "");

// Get an Oid from the ID string
Oid id = new Oid(idString);

// Create a document with the ID we want to find
var queryDoc = new Document { { "_id", id } };

// Query the db for a document with the required ID 
var resultDoc = db["database"]["collection"].FindOne(queryDoc);
db.Disconnect();

// Print the name of the document to prove it worked
Console.WriteLine(resultDoc["name"].ToString());

Altri suggerimenti

var spec = new Document {{ "_id", ObjectId.Parse (id)}};

var doc = mc.FindOne (SPEC);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top