Aggregate match pipeline not equal to in MongoDB
Asked Answered
R

1

12

I am working on an aggregate pipeline for MongoDB, and I am trying to retrieve items where the user is not equal to a variable.

For some reason, I couldn't make it work. I tried to use $not, $ne and $nin in different possible way but can't make it to work.

This is how it looks like:

Data sample:

[{
    "_id": { "$oid": "565674e2e4b030fba33d8fdc" },
    "user": { "$oid": "565674832b85ce78732b7529" }
}, {
    "_id": { "$oid": "565674e2e4b030fba33d8fdc" },
    "user": { "$oid": "565674832b85ce78732b7529" }
}, {
    "_id": { "$oid": "565674e2e4b030fba33d8fdc" },
    "user": { "$oid": "56f9dfc5cc03ec883f7675d0" }
}]

Pipeline sample (simplified for this question):

Where req.query.user.id = "565674832b85ce78732b7529"

collection.aggregate([
    {
        $match: {
            user: {
                $nin: [ req.query.user.id ],
            }
        }
    }
]

This should return only the last item.

Do you have any idea how to retrieve the data that doesn't match the user?

Thanks

Edit: The following doesn't work either:

collection.aggregate([
    {
        $match: {
            'user.$oid': {
                $nin: [ req.query.user.id ],
            }
        }
    }
]);

I also tried with ObjectID() and mongodb complains: [MongoError: Argument must be a string]

var ObjectID = require('mongodb').ObjectID;

// Waterline syntax here
MyCollection.native(function (err, collection) {
    collection.aggregate([
        {
            $match: {
                'user': {
                    $nin: [ ObjectID(req.query.user.id) ],
                }
            }
        }
    ], function (err, result) {
        console.log(err, result);
    });
});

But this line works in the shell:

db.collection.aggregate([{$match:{"user":{"$nin":[ObjectId("565674832b85ce78732b7529")]}}}])
Rang answered 7/10, 2016 at 6:6 Comment(7)
You are missing "$oid" in the query. So try "user.$oid" instead of user in the used query.Situation
Are you using some kind of custom _id fields, not Mongo's ObjectId instances? Usually you have to $nin: [ ObjectId(req.query.user.id) ] when querying against ObjectId-like fields.Edgeways
I use waterline (sailsjs.org/documentation/reference/waterline-orm) which automatically generate those id.Rang
mongodb does not allow key name start with $ how you save the data with "$oid"?Wingard
Actually, it's not waterline which creates this format. I just found out it's because I use mLab which use MongoDB is strict mode: docs.mongodb.com/manual/reference/mongodb-extended-jsonRang
Have a look at this: #38604029Jess
@Jess OMG this works!!!! You should add this to the answerRang
J
1

Based on the answer here, you can change

var ObjectId = require('mongodb'). ObjectID;

to

var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;
Jess answered 10/10, 2016 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.