2013-05-13 62 views
1

如何使用MongoDB和.NET的C#驅動程序執行以下操作。MongoDB C# - 如何執行以下操作

說我有以下的集合(忽略是否有語法錯誤):

{_id: "2312321321sdd", "Ticker": "AAPL", "CompanyName" : "APPLE", "Viewed": "2013-05-13"} 
{_id: "2312321321sde", "Ticker": "AAPL", "CompanyName" : "APPLE", "Viewed": "2013-05-12"} 
{_id: "2312321321sdf", "Ticker": "GOOG", "CompanyName" : "GOOGLE", "Viewed": "2013-05-12"} 
{_id: "2312321321sdg", "Ticker": "MSFT", "CompanyName" : "MICROSOFT", "Viewed": "2013-05-12"} 
{_id: "2312321321sdh", "Ticker": "MSFT", "CompanyName" : "MICROSOFT", "Viewed": "2013-05-11"} 

使用C#和/或LINQ與MongoDB的驅動程序,我該如何獲得最新的3瀏覽過的商品,但也DISTINCT作爲好吧,所以同一個TICKER沒有雙重的起伏。因此,最好在下面將得到恢復:提前

{_id: "2312321321sdd", "Ticker": "AAPL", "CompanyName" : "APPLE", "Viewed": "2013-05-13"} 
{_id: "2312321321sdf", "Ticker": "GOOG", "CompanyName" : "GOOGLE", "Viewed": "2013-05-12"} 
{_id: "2312321321sdg", "Ticker": "MSFT", "CompanyName" : "MICROSOFT", "Viewed": "2013-05-12"} 

感謝....

+0

也許地圖減少查詢您在地圖上的地圖,你的減少步驟是返回實體與最新的觀看。 – 2013-05-13 02:42:23

+0

也許是這樣的http://stackoverflow.com/questions/12785550/mongo-mapreduce-select-latest-date – 2013-05-13 02:43:55

回答

1

我不能說這一點無論使用LINQ甚至很多C#,但它是你在MongoDB中C#之後是什麼就像今天一樣。不幸的是,Collection.AsQueryable()不會讓你走得更遠。

聚合框架或MapReduce是要走的路。一組不同的代碼需要適度,但這裏是AF:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using MongoDB.Bson; 
using MongoDB.Driver; 
using MongoDB.Driver.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      MongoCollection<Tick> coll = 
       new MongoClient("mongodb://11.11.11.11/test").GetServer() 
                   .GetDatabase("test") 
                   .GetCollection<Tick>("tix"); 

      var group = new BsonDocument 
       { 
        { 
         "$group", 
         new BsonDocument 
          { 
           { 
            "_id", "$CompanyName" 
           }, 
           { 
            "LastViewed", new BsonDocument 
             { 
              { 
               "$max", "$Viewed" 
              } 
             } 
           } 
          } 
        } 
       }; 

      foreach (
       var t in 
        coll.Aggregate(group, 
            new BsonDocument("$sort", new BsonDocument("LastViewed", -1)), 
            new BsonDocument("$limit", 3)) 
         .ResultDocuments) 
      { 
       Console.WriteLine("{0} last viewed {1}", t["_id"], t["LastViewed"]); 
      } 
    } 

    public class Tick 
    { 
     public string Id { get; set; } 
     public string Ticker { get; set; } 
     public string CompanyName { get; set; } 
     public string Viewed { get; set; } 
    } 
} 
+0

謝謝Nik .... ....作品...這是有效的嗎? – 2013-05-13 05:03:46

+0

@MrJones,不能說,但它是服務器端,你不會有50k代理問題;我會把一個降序的索引放在了視圖上(這與我在上面做的不一樣,應該是一個實際的'$ date');我也會索引公司名稱,因爲你可能負擔得起;不幸的是,我不知道如何確保AF的操作只是索引,但爲此拍攝並檢查配置文件dbs,以防他們_將告訴 – 2013-05-13 17:50:25

相關問題