场景: 需要获取嵌套数组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