Popular blog tags

1.Mongodb lookup

https://blog.csdn.net/DDKii/article/details/81504805

user

{
    "_id" : ObjectId("5b69062240a6d80a6cece003"),
    "name" : "小明",
    "age" : 28,
    "createtime" : ISODate("2018-08-07T02:38:26.601Z"),
    "_class" : "com.xiangpeng.bo.UserBo"
}

orders

/* 1 */
{
    "_id" : ObjectId("5b69062240a6d80a6cece004"),
    "uid" : ObjectId("5b69062240a6d80a6cece003"),
    "money" : 10.0,
    "createtime" : ISODate("2018-08-07T02:38:26.601Z"),
    "produce" : "产品1",
    "_class" : "com.xiangpeng.bo.OrderBo"
}

/* 2 */
{
    "_id" : ObjectId("5b6a5711c2eee4295c63768e"),
    "uid" : ObjectId("5b69062240a6d80a6cece003"),
    "money" : 20.0,
    "produce" : "产品2",
    "createtime" : ISODate("2018-08-07T02:38:26.601Z"),
    "_class" : "com.xiangpeng.bo.OrderBo"
}

 

db.user.aggregate([{$lookup:{from:"orders",localField:"_id",foreignField:"uid",as:"orders"}}])

output

{
    "_id" : ObjectId("5b69062240a6d80a6cece003"),
    "name" : "小明",
    "age" : 28,
    "createtime" : ISODate("2018-08-07T02:38:26.601Z"),
    "_class" : "com.xiangpeng.bo.UserBo",
    "orders" : [ 
        {
            "_id" : ObjectId("5b69062240a6d80a6cece004"),
            "uid" : ObjectId("5b69062240a6d80a6cece003"),
            "money" : 10.0,
            "createtime" : ISODate("2018-08-07T02:38:26.601Z"),
            "produce" : "产品1",
            "_class" : "com.xiangpeng.bo.OrderBo"
        }, 
        {
            "_id" : ObjectId("5b6a5711c2eee4295c63768e"),
            "uid" : ObjectId("5b69062240a6d80a6cece003"),
            "money" : 20.0,
            "produce" : "产品2",
            "createtime" : ISODate("2018-08-07T02:38:26.601Z"),
            "_class" : "com.xiangpeng.bo.OrderBo"
        }
    ]
}

2.Projection

  #region custom extend 

        /// <summary>
        /// GetViewCount 已优化,改为原子操作
        /// </summary>
        /// <param name="blogPostId"></param>
        /// <returns></returns>
        public int UpdateViewCount(string blogPostId)
        {

            //更新点击数
            Task.Run(() =>
            {
                var update = new UpdateDefinitionBuilder<BlogPost>().Inc(x => x.ViewCount, 1);
                var result = _blogPostRepository.Collection.UpdateManyAsync(x => x.Id == new ObjectId(blogPostId), update).Result;
                _cacheManager.RemoveByPattern(string.Format(BLOGPOST_BY_ID_KEY, blogPostId));
            });

            //获取点击数
            //filter
            var filter = Builders<BlogPost>.Filter.Eq(x => x.Id, new ObjectId(blogPostId));

            //projection
            var projection = Builders<BlogPost>.Projection.Include(x => x.ViewCount);


            var results = _blogPostRepository.Collection.Find(filter)
                             .Project<BlogPost>(projection)
                             .FirstOrDefault();

            return results.ViewCount;



        }


       
        #endregion