B
B
Bruto2021-07-30 11:26:16
Node.js
Bruto, 2021-07-30 11:26:16

How to use $all in mongoDB aggregation?

There are 2 tables, and I take documents from them through aggregation.
I take from the second table like this:

let employees = await models.employee.aggregate([
    {
      $match: {
        login: login.toLowerCase(),
      },
    },
    {
      $lookup: {
        from: "positiontypes",
        let: {
          position: "$position",
          function: "$function",
          bloc: "$bloc",
          specialProperties: "$specialProperties",
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ["$$position", "$position"] },
                  { $eq: ["$$function", "$function"] },
                  { $eq: ["$$bloc", "$bloc"] },
                  {
                    $eq: [
                      "$$specialProperties",
                      "$specialProperties",
                    ],
                  },
                ],
              },
            },
          },
        ],
        as: "positiontype",
      },
    },
  ]);

I'm checking for equality between specialProperties from the first table and specialProperties from the second table. It works, only I don't need an equivalence, but an occurrence ($all).
If you use $all, it gives an error, waits for an array to enter, and I give a string. That is, the variable is treated as a string. How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bruto, 2021-07-30
@BruTO8000

Figured out this query:

let employees = await models.employee.aggregate([
    {
      $match: {
        login: login.toLowerCase(),
      },
    },
    {
      $lookup: {
        from: "positiontypes",
        let: {
          position: "$position",
          function: "$function",
          bloc: "$bloc",
          specialProperties: "$specialProperties",
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ["$$position", "$position"] },
                  { $eq: ["$$function", "$function"] },
                  { $eq: ["$$bloc", "$bloc"] },
                  {
                    $allElementsTrue: {
                      $map: {
                        input: "$$specialProperties",
                        as: "elem",
                        in: {
                          $and: {
                            $in: [
                              "$$elem",
                              "$specialProperties",
                            ],
                          },
                        },
                      },
                    },
                  },
                ],
              },
            },
          },
        ],
        as: "positiontype",
      },
    },	]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question