2010-03-16 30 views
10

Utilizzando il driver MongoDB C# (http://github.com/samus/mongodb-csharp), sembra che non sia possibile ottenere i dati da ObjectId. Sotto il comando che sto usando:MongoDB C# Driver impossibile da trovare per ID oggetto?

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

Ho provato anche questo:

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

Entrambi restituiscono nulla. Nel frattempo, se lo interrogo dalla console di mongo, restituisce il risultato previsto.

La mia domanda è: il driver supporta effettivamente la ricerca di ObjectId?

Grazie ..

risposta

11

Supporta il recupero tramite ID oggetto. La tua variabile id dovrebbe essere un Oid. È il tipo corretto?

Ecco un programma completo che sarà

  • Connetti a Mongo
  • inserire un documento
  • Fetch 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()); 
+0

@Ant: puoi elaborare per favore? Vuoi dire qualcosa del genere? var spec = new Document {{"Oid", id}}; – heisthedon

+0

tu sei campione .. funziona :) grazie per il tuo aiuto .. – heisthedon

+0

è questo utilizzando driver ufficiale o Norm? –

0

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

var doc = mc.FindOne (spec);

+0

Potresti per favore elaborare più la tua risposta aggiungendo un po 'più di descrizione della soluzione che fornisci? – abarisone

Problemi correlati