Daniyal
Daniyal

Reputation: 87

MongoDB - Lookup with pipeline get error: $nin needs an array

Hello everyone I am having some trouble basically I am getting

$nin needs an array

even after passing an array but using a variable when attempting to run the following query.

I want to get documents from a collection numberData that contains a property value which is not assigned to an array in another collection named assignedData.

Example of numbersData docs are given below:

/* 1 */
{
    "_id" : ObjectId("61f2b5923327b3f6f4dad27e"),
    "value" : 1.0
}

/* 2 */
{
    "_id" : ObjectId("61f2b5923327b3f6f4dad27f"),
    "value" : 2.0
}

/* 3 */
{
    "_id" : ObjectId("61f2b5923327b3f6f4dad280"),
    "value" : 3.0
}

/* 4 */
{
    "_id" : ObjectId("61f2b5923327b3f6f4dad281"),
    "value" : 4.0
}

and the contents of assignedData are given below:

/* 1 */
{
    "_id" : ObjectId("61f2b5e43327b3f6f4dad282"),
    "name" : "john",
    "assigned" : [ 
        1.0, 
        4.0
  ]
}

The query I used:

db.assignedData.aggregate([
    {
        //i only want to get single doc from assigned data
        //so using this match
        $match: {
            _id: ObjectId("61f2b5e43327b3f6f4dad282")

        },
    },
    {
        $lookup: {
            from: 'numbersData',
            let: { aArr: "$assigned" },
            pipeline: [
                {
                    $match: {
                        //here i am using $$maArr
                        //which is refering to assigned array
                        value:
                        {
                            $nin: "$$aArr"
                        }
                    }
                }
            ],

            as: 'matchData'
        }
    }
])

After running this query I got the error:

$nin needs an array

I don't know why please suggest me solution if you can.

Upvotes: 1

Views: 1427

Answers (1)

Yong Shun
Yong Shun

Reputation: 51240

From Join Conditions and Subqueries on a Joined Collection section (refer to the table),

let

A $match stage requires the use of an $expr operator to access the variables. The $expr operator allows the use of aggregation expressions inside of the $match syntax.

Instead of using $nin operator, change as below:

{
  $match: {
    $expr: {
      $not: {
        $in: [
          "$value",
          "$$aArr"
        ]
      }
    }
  }
}

Sample Mongo Playground

Upvotes: 4

Related Questions