Skip to content

Instantly share code, notes, and snippets.

@hassansin
Last active August 29, 2015 14:25
Show Gist options
  • Save hassansin/1ff75e99132af04e2c64 to your computer and use it in GitHub Desktop.
Save hassansin/1ff75e99132af04e2c64 to your computer and use it in GitHub Desktop.
Mongoose by Examples
/*
Stream / QueryStreams
----------------------------
Ref: http://mongoosejs.com/docs/api.html#querystream_QueryStream
one chunk == one document
*/
readable = Model.where('created').gte(twoWeeksAgo).stream();
readable = Model.find().stream({ transform: function(doc){
return JSON.stringify(doc);
}});
readable
.on('data',function(doc){
console.log(doc.toObject())
})
.on('error',function(){})
.on('close',function(){})
.pipe(writable)
/*
Get the first matching element in an Array:
---------------------------
Ref: http://docs.mongodb.org/manual/reference/operator/projection/positional/#proj._S_
Check limitation: only one array field allowed.
*/
Project.find({'majorsector_percent.Percent': 70}, {_id:0,'majorsector_percent.$':1},function(err,docs){
console.log(docs)
})
*/
/*
Select embedded array or nested array fields as top-level document
-------------------------------------------------------------------
Example Schema:
{
name: String,
states: [{
name: String,
cities: [{
name: String,
schools: [{
name: String,
addresss: String
}]
}]
}]
}
ref:
*/
//get a city as a top-level document:
Country.aggregate([
//match by city _id and reduce the no of documents for the next pipeline stages
{$match : {'states.cities._id': "55bab42fb768129caa039b4b" } },
//deconstruct states array
{$unwind: '$states'},
//deconstruct cities array
{$unwind: '$states.cities'},
//match again in the deconstructed document list
{$match : {'states.citites._id': "55bab42fb768129caa039b4b" } },
//project the fields
{$project :
{
_id: "$states.cities._id",
name: "$states.cities.name",
schools : "$states.cities.schools"
}
}
])
/*
Group by a key and return the first document from each group:
*/
db.zips.aggregate(
[
{
$sort: { state: 1, city: 1 }
},
{
$group:
{
_id: "$state",
city: { $first: "$$CURRENT" }
}
},
{
$project :
{
_id: "$city._id",
city: "$city.city"
}
}
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment