Group and count by month

You need to use the $month keyword in your group. Your new Date().getMonth() call will only happen once, and will try and create a month out of the string “$bookingdatetime”. db.booking.aggregate([ {$group: { _id: {$month: “$bookingdatetime”}, numberofbookings: {$sum: 1} }} ]);

How to insert a document with date in mongo?

The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to “example” Date now = new Date(); BasicDBObject timeNow = new BasicDBObject(“date”, now); example.insert(timeNow); If you are looking for a way to use the “server” time in operations, there is the $currentDate operator, but this works with “updates”, so … Read more

Create unique autoincrement field with mongoose [duplicate]

const ModelIncrementSchema = new Schema({ model: { type: String, required: true, index: { unique: true } }, idx: { type: Number, default: 0 } }); ModelIncrementSchema.statics.getNextId = async function(modelName, callback) { let incr = await this.findOne({ model: modelName }); if (!incr) incr = await new this({ model: modelName }).save(); incr.idx++; incr.save(); return incr.idx; }; const … Read more

How to I get Spring-Data-MongoDB to validate my objects?

First make sure that you have JSR-303 validator on classpath, for example: <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> If you use Java config, the way to go is to create 2 beans: @Bean public ValidatingMongoEventListener validatingMongoEventListener() { return new ValidatingMongoEventListener(validator()); } @Bean public LocalValidatorFactoryBean validator() { return new LocalValidatorFactoryBean(); } VoilĂ ! Validation is working now.

mongodb schema design for blogs

Article { “_id” : “A”, “title” : “Hello World”, “user_id” : 12345, “text” : ‘My test article’, “comments” : [ { ‘text’ : ‘blah’, ‘user_id’ : 654321, ‘votes’ : [987654]}, { ‘text’ : ‘foo’, ‘user_id’ : 987654, ‘votes’ : [12345, 654321] }, … ] } The basic premise here is that I’ve nested the Comments … Read more

How to create a Mongo Docker Image with default collections and data?

The problem was that information could not be saved on /db/data, so I’ve created a solution creating my own data directory. # Parent Dockerfile https://github.com/docker-library/mongo/blob/982328582c74dd2f0a9c8c77b84006f291f974c3/3.0/Dockerfile FROM mongo:latest # Modify child mongo to use /data/db2 as dbpath (because /data/db wont persist the build) RUN mkdir -p /data/db2 \ && echo “dbpath = /data/db2” > /etc/mongodb.conf \ … Read more

Mongo $in operator performance

It can be fairly efficient with small lists (hard to say what small is, but at least into the tens/hundreds) for $in. It does not work like app-engine since mongodb has actual btree indexes and isn’t a column store like bigtable. With $in it will skip around in the index to find the matching documents, … Read more