还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

MongoDB仿关系型数据库Group聚合例子

来源:清泛原创     2015-07-21 22:57:14    人气:     我有话说( 0 人参与)

MongoDB Group,max仿关系型数据库例子,通过BsonJavaScript脚本实现。相当的SQL:select * from GroupDemo a right join (select userName,max(date) maxdate from GroupDemo group by userName) b on a date=b maxdate

namespace MongoGroupDemo
{
    class Program
    {
        private static string MongoConnStr = "mongodb://172.16.86.53:27017";

        /// <summary>
        /// MongoDB Group,max仿关系型数据库例子
        /// 需求:锯齿状数据表,取所有用户最近一天的数据
        /// 
        ///
        static void Main(string[] args)
        {
            InitData();

            // 取最近一天的数据
            Dictionary dic = new Dictionary();
            dic["_userName"] = ""; // 与原字段名区分开
            dic["_date"] = "";
            dic["_data"] = "0";

            MongoServer server = new MongoClient(MongoConnStr).GetServer();
            MongoDatabase db = server.GetDatabase("admin");
            var docs = db.GetCollection("GroupDemo").Group(null, new GroupByBuilder(new string[] { "userName" }), 
                BsonDocument.Create(dic),
                BsonJavaScript.Create("function(obj,prev){if(prev._date < obj.date){prev._userName=obj.userName; prev._date=obj.date; prev._data=obj.data;}}"),
                BsonJavaScript.Create("function(obj){ obj.userName=obj._userName; obj.date=obj._date; obj.data=obj._data; delete obj._userName; delete obj._date;delete obj._data; }")).ToList();

            if (docs != null)
            {
                foreach (var doc in docs)
                    Console.WriteLine(doc);
            }
        }

        /// 
        /// 初始化缓存数据
        /// 
        private static void InitData()
        {
            try
            {
                MongoServer server = new MongoClient(MongoConnStr).GetServer();
                MongoDatabase db = server.GetDatabase("admin");

                // 初始化
                if (db.CollectionExists("GroupDemo"))
                    db.GetCollection("GroupDemo").Drop();

                db.GetCollection("GroupDemo").Save(CreateBsonDoc("u1", new DateTime(2015, 7, 20), 100));
                db.GetCollection("GroupDemo").Save(CreateBsonDoc("u1", new DateTime(2015, 7, 22), 200));

                db.GetCollection("GroupDemo").Save(CreateBsonDoc("u2", new DateTime(2015, 5, 22), 100));
                db.GetCollection("GroupDemo").Save(CreateBsonDoc("u2", new DateTime(2015, 6, 22), 200));
                db.GetCollection("GroupDemo").Save(CreateBsonDoc("u2", new DateTime(2015, 7, 23), 300));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static BsonDocument CreateBsonDoc(string userName, DateTime date, decimal data)
        {
            BsonDocument doc = new BsonDocument();

            doc.Add("_id", Guid.NewGuid().ToString("N"));
            doc.Add("userName", userName);
            doc.Add("date", date);
            doc.Add("data", (double)data);

            return doc;
        }
    }
}
运行结果:
{ "userName" : "u1", "date" : ISODate("2015-07-21T16:00:00Z"), "data" : 200.0 }
{ "userName" : "u2", "date" : ISODate("2015-07-22T16:00:00Z"), "data" : 300.0 }

完整的工程(vs 2012)代码点此下载
更多的Group聚合相关资料请查看官方文档

MongoDB 聚合 Group

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: