Home > Back-end >  Expression $ne takes exactly 2 arguments. 1 were passed in
Expression $ne takes exactly 2 arguments. 1 were passed in

Time:12-29

I have this to query in db :

const hasUsedVideo = await db.SessionCard.findOne({ movie: Card.movie, unit: Card.unit, video: Card.video }, { _id: { $ne: Card._id } }, { _id: 1 } ).lean();

But I get this error:

MongoError: Expression $ne takes exactly 2 arguments. 1 were passed in.

I don't know how to fix this?

CodePudding user response:

@nimrod serok provides the right guidance in the comments, which I'll copy below for completeness. This answer is just going to outline why you are receiving that error.

The solution to the problem is to include the predicate on _id in the rest of the object that comprises the first argument for the findOne() operation. So instead of:

const hasUsedVideo = await db.SessionCard.findOne(
  { movie: Card.movie, unit: Card.unit, video: Card.video }, 
  { _id: { $ne: Card._id } }, 
  { _id: 1 } 
).lean();

It should be:

const hasUsedVideo = await db.SessionCard.findOne(
  { movie: Card.movie, unit: Card.unit, video: Card.video,  _id: { $ne: Card._id } }, 
  { _id: 1 } 
).lean();

As currently written in the question, the separate second argument (of { _id: { $ne: Card._id } }) is being parsed as the projection argument (instead of the intended projection of { _id: 1 }. The projection argument accepts aggregation expressions and syntax as of version 4.4. This is relevant to the error that you were receiving because there are two different $ne operators in MongoDB:

This is why your usage of _id: { $ne: Card._id } was triggering the error about $ne requiring 2 arguments, because the aggregation variant of the operation does require that.

Mongoplayground will complain about the syntax in the question stating that a maximum of 2 arguments are expected for find() (in the shell implementation). By contrast, the syntax provided by @nimrod serok executes successfully.

  • Related