如何使用MongoDB和.NET的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 :(得分: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; }
}
}