检索数组中不等于ObjectID的排序值

问题描述 投票:0回答:1

这是我的电影数据库架构:

我有这段代码,它检索按创建日期降序排列的对象数组

title
reviews
(工作):

db.films.findOne({ _id: ObjectId('64d69473da87c0c91ae7c596') }, 
     {title:1, reviews:{$sortArray:{input:"$reviews", sortBy:{creationdate:-1}}} } )

我正在尝试扩展它以查找该元素的所有评论不等于特定的

userid

db.films.findOne(
      { _id: ObjectId("64d69473da87c0c91ae7c596") },
      {
        title: 1,
        updatedreviews: {
          $sortArray: {
            input: [
              {
                $cond: [
                  {
                    $not: {
                      $in: [
                        ObjectId("64d95f9b4ce0a13e8fc37567"),
                        "$reviews.userid",
                      ],
                    },
                  },
                  "$reviews",
                  null,
                ],
              },
            ],
            sortBy: { "$reviews.creationdate": -1 },
          },
        },
      }
    );

它不起作用:它正在检索

null
。我尝试了相反的操作,等于
$in
特定的
userid
但它返回了所有评论:

db.films.findOne(
      { _id: ObjectId("64d69473da87c0c91ae7c596") },
      {
        title: 1,
        updatedreviews: {
          $sortArray: {
            input: [
              {
                $cond: [
                  {
                      $in: [
                        ObjectId("64d95f9b4ce0a13e8fc37567"),
                        "$reviews.userid",
                      ],
                  },
                  "$reviews",
                  null,
                ],
              },
            ],
            sortBy: { "$reviews.creationdate": -1 },
          },
        },
      }
);

关于如何解决此问题并检索不是由该特定用户的

ObjectId
做出的所有评论的任何想法吗?

mongodb mongodb-query
1个回答
2
投票

您应该使用

$filter
运算符来过滤
reviews
数组中的匹配元素。

db.films.findOne({
  _id: ObjectId("64d69473da87c0c91ae7c596")
},
{
  title: 1,
  updatedreviews: {
    $sortArray: {
      input: {
        $filter: {
          input: "$reviews",
          cond: {
            $ne: [
              ObjectId("64d95f9b4ce0a13e8fc37567"),
              "$$this.userid"
            ]
          }
        }
      },
      sortBy: {
        "creationdate": -1
      }
    }
  }
})

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.