gpt4 book ai didi

arrays - 如何使用吗啡过滤mongo文档中的嵌入数组

转载 作者:可可西里 更新时间:2023-11-01 10:52:15 25 4
gpt4 key购买 nike

鉴于我的个人资料数据如下所示,我想找到 userName 和 productId 组合的个人资料 并且只返回带有该产品相应契约(Contract)的配置文件。

{
"firstName": "John",
"lastName": "Doe",
"userName": "john.doe@gmail.com",
"language": "NL",
"timeZone": "Europe/Amsterdam",
"contracts": [
{
"contractId": "DEMO1-CONTRACT",
"productId": "ticket-api",
"startDate": ISODate('2016-06-29T09:06:42.391Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "ticket",
"permission": "createTicket"
},
{
"activity": "ticket",
"permission": "updateTicket"
},
{
"activity": "ticket",
"permission": "closeTicket"
}
]
}
]
},
{
"contractId": "DEMO2-CONTRACT",
"productId": "comment-api",
"startDate": ISODate('2016-06-29T10:27:45.899Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "comment",
"permission": "createComment"
},
{
"activity": "comment",
"permission": "updateComment"
},
{
"activity": "comment",
"permission": "deleteComment"
}
]
}
]
}
]
}

我设法找到了如何从命令行执行此操作的解决方案。但我似乎找不到使用 Morphia(最新版本)实现此目的的方法。

db.Profile.aggregate([
{ $match: {"userName": "john.doe@gmail.com"}},
{ $project: {
contracts: {$filter: {
input: '$contracts',
as: 'contract',
cond: {$eq: ['$$contract.productId', "ticket-api"]}
}}
}}
])

这就是我目前所拥有的。非常感谢任何帮助

Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression(??))

注意...同时我找到了另一种不使用聚合管道的解决方案。

    public Optional<Profile> findByUserNameAndContractQuery(String userName, String productId) {
DBObject contractQuery = BasicDBObjectBuilder.start(Contract._productId, productId).get();
Query<Profile> query =
getDatastore()
.createQuery(Profile.class)
.field(Profile._userName).equal(userName)
.filter(Profile._contracts + " elem", contractQuery)
.retrievedFields(true, Profile._contracts + ".$");
return Optional.ofNullable(query.get());
}

最佳答案

我终于找到了过滤嵌入式数组的最佳方法(假设我只想从数组返回最多 1 个元素)。

db.Profile.aggregate([
{ $match: {"userName": "john.doe@gmail.com"}},
{ $unwind: "$contracts"},
{ $match: {"contracts.productId": "comment-api"}}
])

关于arrays - 如何使用吗啡过滤mongo文档中的嵌入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38196963/

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