users.aggregate

an anonymous user · May 09, 2024
db.createCollection("users");
db.createCollection("notifications");
db.users.insertMany([
    {
      "_id": ObjectId("5a934e000102030405000005"),
      "name": "bob",
      "notifications": [ObjectId("5a934e000102030405000001"), ObjectId("5a934e000102030405000002"),ObjectId("5a934e000102030405000003"), ObjectId("5a934e000102030405000004")]
    },
    {
      "_id": ObjectId("5a934e000102030405000006"),
      "name": "sally",
      "notifications": [ObjectId("5a934e000102030405000008")]
    }
]);
db.notifications.insertMany([
    {
      "_id": ObjectId("5a934e000102030405000001"),
      "type": "follow_request",
      "name": "A"
    },
    {
      "_id": ObjectId("5a934e000102030405000002"),
      "type": "follow_request",
      "name": "B"
    },
    {
      "_id": ObjectId("5a934e000102030405000003"),
      "type": "follow_request",
      "name": "C"
    },
    {
      "_id": ObjectId("5a934e000102030405000004"),
      "type": "dont_follow",
      "name": "D"
    }
]);
db.users.aggregate([
  {
    $match: {
      _id: ObjectId("5a934e000102030405000005")
    }
  },
  {
    $lookup: {
      from: "notifications",
      localField: "notifications",
      foreignField: "_id",
      as: "notifications"
    }
  },
  {
    $set: {
      privacyStatus: "value-here",
      notifications: {
        $map: {
          input: {
            $filter: {
              input: "$notifications",
              cond: {
                $ne: [
                  "$$this.type",
                  "follow_request"
                ]
              }
            }
          },
          as: "n",
          in: "$$n._id"
        }
      }
    }
  },
  {
    $merge: {
      into: "users"
    }
  }
])
db.users.find({});
Output

Comments

Please sign up or log in to contribute to the discussion.