2012-06-19 122 views
2

我知道,這似乎是一個非常愚蠢的問題。但不管怎麼說。如何在沒有獲取整個文檔的情況下獲得字段值?

拉特說,我有這樣的結構的文件集:

{ 
    _id: idvalue, 
    name: namevalue, 
    location: 
    { 
    long: longvalue, 
    lat: latvalue 
    } 
} 

,當然,在C#序列化類。

我需要獲取由_id指定的文檔的位置。

我試圖做到這一點的方式如下:

var documentLocation = collection.FindOne("_id", new ObjectId(id)).Location; 

但是,在這種情況下,整個文件會從數據庫中取。我只想採用json的「位置:{long:longvalue,lat:latvalue}」部分。

我該怎麼做?

回答

2

您應該使用Find而不是FindOneFindOne內部調用Find方法如下:

return Find(query).SetLimit(1).FirstOrDefault() 

這意味着你無法通過FindOne改變MongoCursor。但要指定驅動程序應返回的字段(通過SetFields),您需要訪問mongo遊標。

此外,當您指定字段驅動程序仍返回整個對象(不只是位置),但除指定的所有字段將爲空/空。

所以,最終的查詢:

var documentLocation = collection.Find("_id", new ObjectId(id)) 
           .SetFields(Fields.Include("Location")) 
           // single if you sure that this document always in db 
           .Single() 
           .Location; 

而且驅動程序將總是返回_id域,即使你沒有明確指定。

+0

非常感謝!我想使用Find,但是我對SetField感到困惑,因爲我認爲它只是給指定的字段賦值。現在它的目的清楚了我!再次感謝! –

1

我想你可以用Mongo遊標對象上的Cursor和setFields方法來做到這一點。

var cursor = collection.FindAs<DocType>(Query.EQ("_id", new ObjectId(id)); 
cursor.SetFields(Fields.Include("location"); 
var items = cursor.ToList(); 

現在我不是100%確定它能正確工作,但它應該在附近。

+0

謝謝,肖恩!我明白了基本的想法。 SetField()對我來說不是很清楚,但現在沒關係。 –

相關問題