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

Sha*_*aft 3 mongodb spring-data-mongodb

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

private String userId;
private String username;
private Date created;
private List<Comment> comments = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

Comment 有这样的领域:

private String userId;
private String username;
private String message;
private Date created;
Run Code Online (Sandbox Code Playgroud)

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

{
  "userId" : "%some_userId%",
  "date" : "%some_date%",
  "commentsQty" : 100,
  "isCommented" : true
}
Run Code Online (Sandbox Code Playgroud)

我的聚合看起来像这样:

{ "aggregate" : "%entityName%" , "pipeline" : [
   { "$project" : { 
              "username" : 1 , 
              "userId" : 1 , 
              "created" : 1 , 
              "commentQty" : { "$size" : [ "$comments"]}}}]}
Run Code Online (Sandbox Code Playgroud)

它工作正常.但我还需要检查,IF注释数组包含一些注释,具体的userId.我尝试了这个,但它无法执行:

{ "aggregate" : "%entityName%" , "pipeline" : [
   { "$project" : { 
              "username" : 1 , 
              "userId" : 1 ,
              "created" : 1 , 
              "commentQty" : { "$size" : [ "$comments"]} ,
              "isCommented" : { "$exists" : [ "$comments.userId" , "5475b1e45409e07b0da09235"]}}}]}
Run Code Online (Sandbox Code Playgroud)

有这样的消息: Command execution failed: Error [exception: invalid operator '$exists']

怎么做这样的检查?

UPD:也试过运算符$in和类似的,但它们对于队列有效,而不是聚合.

Bat*_*eam 5

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

目前$exists,该aggregation管道中没有运营商.

编辑:

写出更好的答案:

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

  • 如果用户真的对帖子发表了评论,请使用$setIntersectionoperator来获取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]}}}
])
Run Code Online (Sandbox Code Playgroud)

上一个答案:

  • Unwind 评论.
  • Project一个额外的字段isCommented对于每个评论文档,检查它是否具有userId我们正在搜索的文档,如果它具有相应的userId,则将该变量设置为1else 0.
  • Group将文档再次合并在一起isCommented,如果是的话> 0,将该用户ID的文档存在于该组中,否则不存在.
  • Project 相应的领域.

代码:

{ "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"}}},
    ]}
Run Code Online (Sandbox Code Playgroud)


Tec*_*dom 5

如果您想检查精确的单个值(即特定的登录userId),只需使用$in运算符:

let loggedInUserId = "user1";

db.entities.aggregate([
{$project:{
    "userName": 1,
    "isCommentedByLoggedInUser": {
        $in : [ loggedInUserId, "$comments.userId" ]
    },
])
Run Code Online (Sandbox Code Playgroud)

就是这样。

注意:如果您不希望每个文档都有注释数组,请用$ifNull运算符将​​其包装起来,并生成一个空数组:

$in : [ loggedInUserId, { "$ifNull": [ "$comments.userId", [] ] } ]
Run Code Online (Sandbox Code Playgroud)

当您需要众多用户(任何逻辑)中的至少一个来满足要求时,BatScream 的出色答案是检查多个值。在我看来,这对于您的情况来说不是必需的,但这是一种很好的方法。

因此,BatScream 提到了聚合方式中的任何逻辑,我将继续聚合方式中的所有逻辑。要查找包含所有特定用户评论的文档,只需使用$setIsSubset运算符:

let manyUsersIdsThatWeWantAll = ["user1", "user2", "user3"];

db.entities.aggregate([
{$project:{
    "userName": 1,
    "isCommentedByAllThoseUsers": {
        $setIsSubset: [
            manyUsersIdsThatWeWantAll, // the needle set MUST be the first expression
            "$comments.userId"
        ]
    },
])
Run Code Online (Sandbox Code Playgroud)