在提出问题以更多地了解MongoDB中的聚合框架后,我终于找到了根据需要进行聚合的方法(感谢一位StackExchange用户)。
所以基本上这是我收藏的一个文档:
{
"_id" : ObjectId("s4dcsd5s4d6c54s6d"),
"items" : [
{
type : "TYPE_1",
text : "blablabla"
},
{
type : "TYPE_2",
text : "blablabla"
},
{
type : "TYPE_3",
text : "blablabla"
},
{
type : "TYPE_1",
text : "blablabla"
},
{
type : "TYPE_2",
text : "blablabla"
},
{
type : "TYPE_1",
text : "blablabla"
}
]
}我的想法是能够只过滤我的集合中的一些元素(避免类型2和类型3)。事实上,我有30多种类型,其中6种是不允许的,但为了简单起见,我做了这个例子。所以命令行中的聚合命令是这样的:
db.history.aggregate([{
$match: {
_id: ObjectId("s4dcsd5s4d6c54s6d")
}
}, {
$unwind: '$items'
}, {
$match: {
'items.type': { '$nin': [ "TYPE_2" , "TYPE_3"] }
}
},
{ $limit: 10 }
]);这样,我就能够检索到这个文档中与TYPE_2和TYPE_3不匹配的10个元素项
但是,当我使用spring数据时,没有输出。我看了一下这个例子来构建我的,但它仍然不能工作。
所以我就这么做了:
Aggregation aggregation = newAggregation(
match(Criteria.where("id").is(myID)),
unwind("items"),
match(Criteria.where("items.type").nin(ignoreditemstype)),
limit(3),
skip(offsetLong)
);
AggregationResults<PersonnalHistory> results = mongAccess.getOperation().aggregate(query,
"items", PersonnalHistory.class);PersonnalHistory用注释@Document(collection = "history")标记,id用@id注释标记
ignoreditemstype是一个包含TYPE_2和TYPE_3的列表
下面是我在聚合的toString方法中拥有的内容:
{
"aggregate" : "__collection__" ,
"pipeline" : [
{ "$match": { "id" : "s4dcsd5s4d6c54s6d"} },
{ "$unwind": "$items"},
{ "$match": { "items.type": { "$nin" : [ "TYPE_2" , "TYPE_3" ] } } },
{ "$limit" : 3},
{ "$skip" : 0 }
]
}我尝试了很多东西(至少有一个答案:),比如删除id或nin:
aggregation = newAggregation(
unwind("items"),
match(Criteria.where("items.type").nin(ignoreditemstype)),
limit(3),
skip(offsetLong)
);
aggregation = newAggregation(
match(Criteria.where("id").is(myid)),
unwind("items")
);当我执行一个简单的查询时获取信息,例如:
query.addCriteria(Criteria.where("id").is(myID));返回我的文档。然而,我有数千个项目。所以我只想要前15个(实际上前15个是最后添加的15个)
你知道我做错了什么吗?
https://stackoverflow.com/questions/41366874
复制相似问题