gpt4 book ai didi

Spring Data mongodb聚合匹配

转载 作者:行者123 更新时间:2023-12-02 04:02:05 26 4
gpt4 key购买 nike

在提出问题以进一步了解 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_2TYPE_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_2TYPE_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 个)

你能看出我做错了什么吗?

最佳答案

是的,看起来您正在传递简单的字符串,而它期待的是 ObjectId

Aggregation aggregation = newAggregation(
match(Criteria.where("_id").is(new ObjectId(myID))),
unwind("items"),
match(Criteria.where("items.type").nin(ignoreditemstype)),
limit(3),
skip(offsetLong)
);

现在的问题是为什么它适用于简单查询,我的回答是因为 spring-data 驱动程序还不够成熟,至少在聚合管道方面没有。

关于Spring Data mongodb聚合匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com