MongoDB C#ドライバーオブジェクトIDで見つけることができませんか?

StackOverflow https://stackoverflow.com/questions/2453513

  •  20-09-2019
  •  | 
  •  

質問

MongoDB C#ドライバーの使用(http://github.com/samus/mongodb-csharp)、ObjectIDでデータを取得できないようです。私が使用しているコマンドの下:

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

私もこれを試しました:

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

どちらも何も返しません。一方、Mongoコンソールから照会すると、期待される結果が返されます。

私の質問は、そのドライバーが実際にObjectIDによるルックアップをサポートしているのですか?

ありがとう..

役に立ちましたか?

解決

オブジェクトIDによるフェッチングをサポートします。 ID変数はOIDである必要があります。それは正しいタイプですか?

これが完全なプログラムです

  • マンゴに接続します
  • ドキュメントを挿入します
  • IDを使用してドキュメントを取り戻します
  • ドキュメントの詳細を印刷します。

// 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());

他のヒント

var spec = new Document {{"_id"、objectid.parse(id)}};

var doc = mc.findone(spec);

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top