Reputation: 1189
This is my mongoose schema:
var userSchema = new mongoose.Schema({
userID: String,
gender: String,
dateCreated: { type: Date, default: Date.now }
})
And this is my query
userSchema.statics.getUser = function(callback){
this.aggregate()
.exec(function(err, result){
callback(result);
});
}
Some users might not have gender added when creating, how can I pull all document using aggregate that does not have the attribute gender populated?
Upvotes: 0
Views: 1908
Reputation: 151112
The results are actually language agnostic so a simple mongo shell should suffice. The results can simply be obtained in a find:
Consider:
> db.user.find().pretty()
{
"_id" : ObjectId("52ecf6b46a8b205baeb2cc58"),
"user" : "neil",
"gender" : "M"
}
{ "_id" : ObjectId("52ecf6c66a8b205baeb2cc59"), "user" : "fabio" }
{
"_id" : ObjectId("52ecf77c6a8b205baeb2cc5a"),
"user" : "markus",
"gender" : "M",
"preference" : "any"
}
This works well for:
> db.user.find({ preference: null }).pretty()
{
"_id" : ObjectId("52ecf6b46a8b205baeb2cc58"),
"user" : "neil",
"gender" : "M"
}
{ "_id" : ObjectId("52ecf6c66a8b205baeb2cc59"), "user" : "fabio" }
And also with $match in aggregate:
> db.user.aggregate([{$match: { prefernce: null }}])
{
"result" : [
{
"_id" : ObjectId("52ecf6b46a8b205baeb2cc58"),
"user" : "neil",
"gender" : "M"
},
{
"_id" : ObjectId("52ecf6c66a8b205baeb2cc59"),
"user" : "fabio"
},
{
"_id" : ObjectId("52ecf77c6a8b205baeb2cc5a"),
"user" : "markus",
"gender" : "M",
"preference" : "any"
}
],
"ok" : 1
}
Look at Aggregation in the MongoDB docs for more information.
Upvotes: 3
Reputation: 146014
You don't need aggregate for this. Just a regular old query will do.
User.find({gender: {$exists: false}}, function (error, users) {/*...*/}};
Upvotes: 0