gpt4 book ai didi

MongoDB 聚合。检查嵌套数组是否包含值

转载 作者:可可西里 更新时间:2023-11-01 09:23:09 26 4
gpt4 key购买 nike

我在实体中有这样的字段:

private String userId;
private String username;
private Date created;
private List<Comment> comments = new ArrayList<>();

Comment 有这样的字段:

private String userId;
private String username;
private String message;
private Date created;

我需要进行聚合,并收到类似这样的信息:

{
"userId" : "%some_userId%",
"date" : "%some_date%",
"commentsQty" : 100,
"isCommented" : true
}

我的聚合看起来像这样:

{ "aggregate" : "%entityName%" , "pipeline" : [
{ "$project" : {
"username" : 1 ,
"userId" : 1 ,
"created" : 1 ,
"commentQty" : { "$size" : [ "$comments"]}}}]}

而且它工作正常。但我还需要检查,如果评论数组包含一些评论,具有特定的 userId。我试过这个,但它无法执行:

{ "aggregate" : "%entityName%" , "pipeline" : [
{ "$project" : {
"username" : 1 ,
"userId" : 1 ,
"created" : 1 ,
"commentQty" : { "$size" : [ "$comments"]} ,
"isCommented" : { "$exists" : [ "$comments.userId" , "5475b1e45409e07b0da09235"]}}}]}

带有这样的消息:命令执行失败:错误 [异常:无效的运算符'$exists']

如何进行这样的检查?

UPD:还尝试了运算符 $in 和类似运算符,但它们对查询有效,对聚合无效。

最佳答案

with such message : Command execution failed: Error [exception: invalid operator '$exists']

当前 $exists运算符在 aggregation 管道中不可用。

编辑:

写出更好的答案:

您可以通过以下方式检查是否有任何用户发表评论:

  • 使用$setIntersection如果用户真的对帖子发表了评论,运算符会获取包含我们正在寻找的 userId 的数组。
  • 申请$size运算符以获取结果数组的大小。
  • 使用$gt运算符检查大小是否大于 0
  • 如果是,则表示存在一个或多个我们要查找的userId的评论,否则不存在。

示例代码:

var userIdToQuery = "2";
var userIdsToMatchAgainstComments = [ObjectId("5475b1e45409e07b0da09235")];

db.t.aggregate([
{$match:{"userId":userIdToQuery}},
{$project:{"userName":1,
"created":1,
"commentQty":{$size:"$comments"},
"isCommented":{$cond:
[{$gt:[
{$size:
{$setIntersection:["$comments.userId",
userIdsToMatchAgainstComments]}}
,0]},
true,false]}}}
])

上一个答案:

  • Unwind 评论。
  • Project 一个额外的字段 isCommented 对于每个评论文档,检查它是否有我们正在搜索的 userId,如果它有相应的userId,然后将变量设置为1,否则为0
  • Group 再次将文档组合在一起,对 isCommented 中的值求和,如果它是 > 0,具有用户 id 的文档存在于 else 组中不是。
  • 相应地投影字段。

代码:

{ "aggregate" : "%entityName%" , "pipeline" :[
{$unwind:"$comments"},
{$project:{
"username":1,
"userId":1,
"created":1,
"comments":1,
"isCommented":{$cond:[{$eq:["$comments.userId",
ObjectId("5475b1e45409e07b0da09235")
]
},
1,
0]}}},
{$group:{"_id":{"_id":"$_id",
"username":"$username",
"userId":"$userId",
"created":"$created"},
"isCommented":{$sum:"$isCommented"},
"commentsArr":{$push:"$comments"}}},
{$project:{"comments":"$commentsArr",
"_id":0,
"username":"$_id.username",
"userId":"$_id.userId",
"created":"$_id.userId",
"isCommented":{$cond:[{$eq:["$isCommented",0]},
false,
true]},
"commentQty":{$size:"$commentsArr"}}},
]}

关于MongoDB 聚合。检查嵌套数组是否包含值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27153948/

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