Posts

Showing posts with the label Mongodb Query

Aggregate/project Sub-document As Top-level Document In Mongo

Answer : When you have many, many fields in the sub-document and occasionally it is updated with new fields, then projection is not a viable option. Fortunately, since 3.4, MongoDB has a new operator called $replaceRoot . All you have to do is add a new stage at the end of your pipeline. db.getCollection('sample').aggregate([ { $replaceRoot: {newRoot: "$command"} }, { $project: {score: 0 } //exclude score field } ]) This would give you the desired output. Note that in case of aggregation (especially after a $group stage) the 'command' document could be an array and could contain multiple documents. In this case you need to $unwind the array first to be able to use $replaceRoot . As you have guessed, $project allows you to do that: db.col.aggregate([ { $project : { _id: "$command._id", name: "$command.name", strike: "$command.strike", duratio...

Bulk Upsert In MongoDB Using Mongoose

Answer : Not in "mongoose" specifically, or at least not yet as of writing. The MongoDB shell as of the 2.6 release actually uses the "Bulk operations API" "under the hood" as it were for all of the general helper methods. In it's implementation, it tries to do this first, and if an older version server is detected then there is a "fallback" to the legacy implementation. All of the mongoose methods "currently" use the "legacy" implementation or the write concern response and the basic legacy methods. But there is a .collection accessor from any given mongoose model that essentially accesses the "collection object" from the underlying "node native driver" on which mongoose is implemented itself: var mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var sampleSchema = new Schema({},{ "strict": false }); va...

Can A $text Search Perform A Partial Match

Answer : MongoDB $text searches do not support partial matching. MongoDB allows text search queries on string content with support for case insensitivity, delimiters, stop words and stemming. And the terms in your search string are, by default, OR'ed. Taking your (very useful :) examples one by one: SINGLE TERM, PARTIAL // returns nothing because there is no world word with the value `Crai` in your // text index and there is no whole word for which `Crai` is a recognised stem db.submissions.find({"$text":{"$search":"\"Crai\""}}) MULTIPLE TERMS, COMPLETE // returns the document because it contains all of these words // note in the text index Dr. Bob is not a single entry since "." is a delimiter db.submissions.find({"$text":{"$search":"\"Craig\" \"Dr. Bob\""}}) MULTIPLE TERMS, ONE PARTIAL // returns the document because it contains the whole word "Craig" an...