Java MongoDB 获取内嵌集合和内嵌集合的长度

场景: 需要获取嵌套数组datas的长度,这里存的是对象

{ 
    ...
    "userid" : "123", 
    "datas" : [
        {
            "id" : "111", 
            "time" : ISODate("2019-05-21T08:12:13.058+0000")
        }, 
        {
            "id" : "222", 
            "time" : ISODate("2019-05-27T02:49:57.090+0000")
        }, 
        {
            "id" : "333", 
            "time" : ISODate("2019-05-30T07:19:13.022+0000")
        }
    ], 
    ...
}

1,mongodb原始命令聚合语句查询语句:

官方文档:

https://docs.mongodb.com/manual/reference/operator/aggregation/project/index.html

https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size

  • $project —— 是常用的管道命令之一:修改输⼊⽂档的结构,如重命名、增加、删除字段、创建计算结果
    Passes along the documents with the requested fields to the next stage in the pipeline. The specified fields can be existing fields from the input documents or newly computed fields.
  • $size
    Counts and returns the total the number of items in an array.
db.Fans.aggregate([
    {
        "$match": {
            "datas": { $exists: true }
        }
    },
    {
        "$project": {
            datasNum: { $size: "$datas" }
        }
    }
])

2,java代码编写:

MongoCollection<Document> collection =
    mongoClient.getDatabase(YOUR_DATABASE_NAME).getCollection(YOUR_COLLECTION_NAME);
List<Document> group = Arrays.asList(
        new Document("$match",
                new Document("userid",
                        new Document("$eq", userid)
                )
        ), new Document("$match",
                new Document("datas",
                        new Document("$exists", true)
                )
        ), new Document("$project",
                new Document("datasSize",
                        new Document("$size", "$datas"))
        )
);
AggregateIterable<Document> aggregate = collection.aggregate(group);
Document document = aggregate.first();
if (document != null) {
    datasSize = (Integer) document.get("datasSize");
}

 


参考来源于:

https://segmentfault.com/q/1010000011543562

https://blog.csdn.net/makang456/article/details/87993122

https://docs.mongodb.com/manual/reference/operator/aggregation/project/index.html

https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size

https://bbs.csdn.net/topics/390924491

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值