I have a query which is working fine when I run it in MongoDB Compass utility:
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published') {return this; } "}
In the same collection or table I have two more fields createBy and userId
Now I want to filter records which have different createdBy than userId. I try this:
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && this.userId != this.createdBy) {return this; } "}
And this also:
{ $where: "if (this.media && this.media.length > 1 && this.status=='Published' && ObjectId(this.userId) != ObjectId(this.createdBy)) {return this; } "}
But none of the above two works. I understand the ObjectId is of type Object and comparing objects with exact same values wont work. Just not getting it how to compare it in mongodb query console.
I think you need .toString()
method to compare two ObjectIds
try :
this.userId.toString()!= this.createdBy.toString()
One other alternative would be to use .equals()
this.userId.equals(this.createdBy)
Read more about .equals() and .toString() here.