2014-06-27 71 views
0

我是MongoDB的新手,我想知道是否可以按照我在數組中指定的順序獲取文檔。我正在使用官方的C#驅動程序。使用C#驅動程序從MongoDB獲取指定順序的文檔

問題描述

我有收集這樣

{ 
    "_id" : "1", 
    "Name" : "Assignment 1" 
} 

{ 
    "_id" : "100", 
    "Name" : "Assignment 100" 
} 

我的ID { "4", "19", "10", "6" }的數組,我需要的是獲取一些文件按照與數組中相同的順序指定的文檔。

這些是我試圖

{ 「_id」:{ 「$在」:[ 「4」, 「19」, 「10」, 「6」]}}的查詢

{ "$or" : [{ "_id" : "4" }, { "_id" : "19" }, { "_id" : "10" }, { "_id" : "6" }] } 

但是這兩個查詢都退回單據按以下順序 enter image description here

但我期望的結果是

enter image description here

現在我面前的唯一選擇是爲數組中的每個元素做出單獨的數據庫請求,我認爲這是個不好的選擇。

你們中的任何人都可以引導我按照我在數組中指定的順序獲取文檔。我正在使用MongoDB C#驅動程序,期待基於C#的答案。

感謝,
卡皮爾

+0

一個更http://stackoverflow.com/questions/3142260/order-of-responses-to-mongodb-in-query – Quaiks

+0

@NeilLunn:謝謝指導我這個問題,我想要一個答案C#和你的答案已經幫助我在c#中實現相同 – wizzardz

回答

0

嗯,我終於成功地使用聚合框架,使這項工作。

這是我實現它的方式。但是如果有人能提出比這更好的方法,我會很高興。

string[] fetchingIds = { "4", "19", "10", "6" }; 

IMongoQuery fetchQuery = Query<Assignment>.In(x => x.Id, fetchingIds); 
BsonDocument match = new BsonDocument { { "$match", fetchQuery.ToBsonDocument() } }; 

BsonDocument currentDocument = null; 
BsonDocument finalDocument = null; 
BsonValue processingDocument = null; 
for (int i = 0; i < fetchingIds.Length; i++) 
{ 
    BsonElement ifStatement = new BsonElement("$eq", new BsonArray(new[] { "$_id", fetchingIds[i] })); 
    BsonArray conditionStatement = new BsonArray(new[] { new BsonDocument(ifStatement), BsonValue.Create(i + 1), -1 }); 
    currentDocument = new BsonDocument("$cond", conditionStatement); 

    if (finalDocument == null) 
    { 
     finalDocument = currentDocument; 
    } 
    else 
    { 
     processingDocument = null; 
     BsonValue tempDoc = finalDocument["$cond"][2] as BsonDocument; 

     if (tempDoc == null) 
     { 
      processingDocument = finalDocument["$cond"]; 
     } 

     while (tempDoc != null) 
     { 
      if ((tempDoc["$cond"][2] as BsonDocument) == null) 
      { 
       processingDocument = tempDoc["$cond"]; 
       tempDoc = null; 
      } 
      else 
      { 
       tempDoc = tempDoc["$cond"][2]; 
      } 
     } 

     processingDocument[2] = currentDocument; 
    } 
} 


BsonDocument project = new BsonDocument { { "$project", new BsonDocument 
                 { 
                  // this will return whose document 
                  {"obj","$$ROOT"}, 
                  {"weight",finalDocument}, 
                 } 
             } }; 

BsonDocument sort = new BsonDocument { { "$sort", new BsonDocument { { "weight", 1 } } } }; 

var result = assignmentCollection.Aggregate(new AggregateArgs 
{ 
    Pipeline = new[] { match, project, sort }, 
}).ToList(); 
相關問題