GsMalhotra
GsMalhotra

Reputation: 1877

Find all except one in mongodb

I want to skip one user particular by using _id and display all others users, I am trying below code its not working:

db.user.find(
    { _id: { $nin: ["5848e9ecaec0f31372816a26"] } },
    { username: 1 }
).pretty()

Upvotes: 9

Views: 9199

Answers (3)

Alen Vlahovljak
Alen Vlahovljak

Reputation: 574

I'm serching here for sockets which are defined which means that users is online. So use $nin:

const indexUsersHelper = async (req, res, next) => {
        try {
            return await db.User.find({ socketId: { $nin: 0 } });
        } catch (err) {
            next(err);
        }
    };

Upvotes: 2

P.Madhukar
P.Madhukar

Reputation: 464

Use ObjectId for _id :

db.user.find( { _id: { $nin: [ObjectId("5848e9ecaec0f31372816a26")] } } )

Upvotes: 13

lomboboo
lomboboo

Reputation: 1233

Short answer: Use $ne for one user db.user.find( {_id:{$ne:"5848e9ecaec0f31372816a26"} }) .

Upvotes: 4

Related Questions