StoredId class is just a POJO with 3 fields: id className (to store the type of object the auto-increment will be done on, but you could store something lese, this is just used to retrieve the adequate increment value, because you could have more than one auto-incremented collection !) value...
node.js,mongodb,mongoose,passport.js
It's because the document object you get back from mongoose doesn't access the properties directly. It uses the prototype chain hence hasOwnProperty returning false (I am simplifying this greatly). You can do one of two things: use toObject() to convert it to a plain object and then your checks will...
javascript,node.js,mongodb,npm
//The route for getting data for the database app.get("/database", function(req, res) { Entry.find({}, function(err, data) {console.log(err, data, data.length); }); }); //The route for posting data on the database app.post("/database", function(req, res) { //test new post var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'}); newMonth.save(function(err) { if (err !== null) {...
$set is not an array update operation. The $set operator replaces the value of a field with the specified value. You just want to use $push by itself, as in .update({_id: id}, {$push: {name: item}}) You can't interpolate object property names in raw object declarations, so if you want to...
Your problem here is that you have missed one of the core concepts of how mapReduce works. The relevant documentation that explains this is found here: MongoDB can invoke the reduce function more than once for the same key. In this case, the previous output from the reduce function for...
First of all the schema you posted is off, should be { album : "album1", pictures: [ 1.jpg, 2.jpg, 3.jpg ] } note "pictures" is an array not an object. You can add to the array with //SAVE DB AlbumPhoto.update({album:'album1'}, {$push: {pictures: "new.jpg"}}, function(err, data){ if(err){ console.log(err); } }) ...
node.js,mongodb,model,populate,auto-populate
When you create an instance of the Post model, you need to assign the _id from the user as an ObjectId, not a string: var ObjectId = require('mongoose').Types.ObjectId; Post.create({ text: 'farheen123', created_by: new ObjectId('5587bb520462367a17f242d2') }, function(err, post) { if(err) console.log("Farheen has got error"+err); else console.log(post); }); ...
You mention in the comments that the underlying issue is an OutOfMemoryException. Answer here suggests paging best practices MongoDB - paging...
It's not "documents" it's "Objects" as is stated, but you would not be the first person to not fully understand the .explain() output. Put simply, you have as part of your index an "array" element (actually the maximum "two" allowed), which means that your index is what we call "MultiKey"....
Looks like you've missed some brackets before $elemMatch: db.items.find( { "$or": [ {"f": {$elemMatch: {"t": "ry", "v": {$gt: 1980}}}}, {"f": {$elemMatch: {"t": "g", "v": {$in: ["Drama"]}}}} ] } ) ...
Yes, Changes made to data in MongoDB shell are permanent but for configuration parameters, they will last only till next restart of instance if they are not specified in config file. MongoDB runs with default values if config file is not specified. You can specify config file as, mongod --config...
JavaScript has no nice notation for creating an object where the keys are variables: var $push_query = {}; $push_query[name] = item; ... {"$push": $push_query} ... ...
Since you're using the mongojs module, you're going to have to connect to the database using the following method db = mongo("127.0.0.1:27017/"+db, collections); ...
There is mistake in your syntax. From mongo version 3.0.0, mongoexport removed the --type = csv option. Use the --type=csv option to specify CSV format for the output. You should use : mongoexport --db tests --collection accounts --type=csv --fields account_number,situses --out coordinates.csv For nested fields you should use : mongoexport...
javascript,mongodb,mongoose,sails.js
I want to give the different privileges for each of user Super admin can access whole DB. Admin can access the data relate to that field User can access the data related to the user. What you need is primarily a document-level access control where a user can access...
I think the driver just doesn't implement the Linq GroupBy method. Use aggregate framework instead. You can find good examples here - MongoDB Aggregation Framework Examples in C# You don't need to link any new libraries the support for the aggregation framework goes with MongoDB C# driver. Hope it helps!...
No. Well, not exactly. A db.collection.find() will give you the documents in the order they appear in the datafiles host of the times, though this isn't guaranteed. Result Ordering Unless you specify the sort() method or use the $near operator, MongoDB does not guarantee the order of query results. As...
A "compound index" which is the correct term for your "link" does not create any performance problems on "read" ( since writing new entries is obviously more information ) than an index just on the single field used in the query. With one exception. If you use a "multi-Key" index...
That's a pretty wide question, partly opinion based. This question should be closed, but I still want to give you some advice. There once was the Active Record pattern, which has been proven to be pretty difficult to maintain. The solution was the DAO pattern, but this adds a lot...
arrays,node.js,mongodb,mongoose,schema
You can use the distinct function to get the unique values across all category array fields of all documents: Article.distinct('category', function(err, categories) { // categories is an array of the unique category values }); Put an index on category for best performance....
Custom bson Marshalling/Unmarshalling works nearly the same way, you have to implement the Getter and Setter interfaces respectively Something like this should work : type Currency struct { value decimal.Decimal //The actual value of the currency. currencyCode string //The ISO currency code. } // GetBSON implements bson.Getter. func (c Currency)...
show dbs is a simple helper. You should use: db.getMongo().getDBs(); So db.getMongo().setSlaveOk();db.getMongo().getDBs() should work....
The GetBSON method should return the value to be marshaled, not the binary data resulting from marshaling it. That's why its first result type is interface{} and not []byte.
You need the positional $ operator in your update portion of the statement: db.getCollection('forms').update( { "_id" : ObjectId("557e8c93a6df1a22041e0879"), "Questions._id" : ObjectId("557e8c9fa6df1a22041e087b") }, { "$push" : { "Questions.$.DataSource" : { "_id" : ObjectId("557e8e5ea6df1a27b403ff6b"), "CreationDate" : ISODate("2015-06-15T08:35:42.923Z"), "IsActive" : true, "Text" : "op", "Value" : "op" } } } ) It identifies...
Attention: Mongo id should be unique as possible in order to scale well. The default ObjectId is consist of a timestamp, machine ID, process ID and a random incrementing value. Leaving it with only the latter would make it collision prone. However, sometimes you badly want to prettify the never-ending...
You should first $unwind records and then match elements like following: db.collection.aggregate({ "$unwind": "$records" }, { "$match": { "records.items": { "$in": ["A428 ", "A429 "] } } }, { "$group": { "_id": "$_id", "records": { "$push": "$records" } } }).pretty() ...
javascript,json,mongodb,meteor,data
Simple use underscores _.extend function. Like this: var newProfile = _.extend( JSON.parse(Assets.getText('test.json')), {user: id} ) Profiles.insert(newProfile) ...
Your code "works' but I think you may have copied-and-pasted something wrong. In particular, you're swapping the use of find() and find_one(). The enter_data() method calls insert() without specifying _id so the driver will invent one for you. That _id ends up being an ObjectId similar to this: { "_id"...
innodb_flush_log_at_trx_commit = 2 Is the winner : 150x faster !!! on standard disk (will try on SSD later)...
As per your output you should required only aggregation on Book collection and the aggregation query as below : db.book.aggregate({ "$group": { "_id": "$authorId", "names": { "$push": "$name" }, "count": { "$sum": 1 } } }, { "$unwind": "$names" }, { "$sort": { "count": 1 } }, { "$project": {...
So after searching for an hour, I have found the solution - i had to look at this post which is not in java but in node.js. Querying a MongoDB based on Mongo ID in a node.js app Thankfully, the language is close to java so I saw that you...
mongodb,mongodb-query,pymongo,aggregation-framework
Well's you can do this using the aggregation framework as follows: collection.aggregate([ { "$project": { "name": 1, "code": 1, "abbreviation": 1, "bill_codes": { "$setUnion": [ "$bill_codes", [] ] } }} ]) The $setUnion operator is a "set" operator, therefore to make a "set" then only the "unique" items are kept...
please try the below query : db.collection.aggregate( [ { "$unwind": "$data.order_goods" }, { "$group" : { "_id" : "$data.order_goods.category", "total": {"$sum":1} } }, { "$project" : { "category" : "$_id" , total : 1 } ] ); ...
In keeping with your current schema (not recommended): First, save the entire document to the client: doc = { _id: 1, projectName: name, managers: [ { managerId: "manager1", status: false, startDate: "startDate", endDate: "endDate" }, { managerId: "manager2", status: false, startDate: "startDate",endDate: "endDate" }, { managerId: "manager3", status: true, startDate:...
java,spring,mongodb,spring-data-mongodb
Per MongoDB reference for $or, your Query should be @Query("{'$or':[ {'type':?0}, {'name':?1} ]}") you'll need to give pass type and name params....
javascript,html,angularjs,mongodb
DOCS Change your factory to service as you are using this factory return an object or primitive type not bind with this app.services('articleFactory', ['$q', '$http', function ($q, $http){ this.getAllArticles = function (){ var deferred = $q.defer(), httpPromise = $http.get ('/entries'); httpPromise.success (function (data){ deferred.resolve (data); }) .error (function (err){ console.log...
javascript,python,mongodb,date
If you can be assured of the format of the input date string AND you are just trying to get a count of unique YYYYMMDD, then just $project the substring and group on it: var data = [ { "name": "buzz", "d1": "2015-06-16T17:50:30.081Z"}, { "name": "matt", "d1": "2018-06-16T17:50:30.081Z"}, { "name":...
javascript,node.js,mongodb,mongoose
Since the address field is not required by Mongoose when you retrieve the Model from the database the field just won't be defined. Thus you won't be able to add an address field. You should check to see if it exists if(member.address === undefined){ member.address.push(new_address); } else{ member.address = [new_address];...
Use fields (?): return MyCollection.find({},{fields:{"MWLink.LinkID": 1}}).fetch(); If you feel you need a bit more power on what comes up you can use map (?) or a transform (?): var transform = function(doc) { return { MWLink : { LinkID: doc.MWLink.LinkID } } } //A transform returns a cursor return MyCollection.find({},...
java,mongodb,mongodb-query,mangodb
You should use aggregation to get result. If you want ActionType wise OrderCount for given date (particular) date then you need to first match start to your date and then group data according to Action.Type. The query will be as following: db.collection.aggregate({ $match: { "SessionTimeStamp.Start": ISODate("2015-06-02T05:36:49.045Z") } }, { $group:...
You can bind mongod only to one IP, with 0.0.0.0 being the alias for "listen on all available network interfaces". So either use bind_ip=127.0.0.1 to listen to the loop back interface or bind_ip=<someIP> to listen to that IP only or bind_ip=0.0.0.0 to listen to all available IPs on the system....
It all depends on usage patterns. First, you normalize: 1 conversation has many messages, 1 message belongs to 1 conversation. That means you've got a 1-to-many (1:M) relationship between conversations and messages. In a 1:M relationship, the SQL standard is to assign the "1" as a foreign key to each...
BsonDocument provides flexible way to represent JSON/BSON in C#. Creating BsonDocument is similar to creating JSON objects. Simple document new BsonDocument("name", "Joe") creates JSON { "name" : "Joe" } More complex document new BsonDocument { {"Name", "Joe"}, { "Books", new BsonArray(new[] { new BsonDocument("Name", "Book1"), new BsonDocument("Name", "Book2") }) }...
Yes, this is the expected behavior. Since the MapReduceIterable is a fluent interface, there must be some way to signal the driver that it's time to actually do the map-reduce, and currently the only way to do that is to start iterating. If you really don't need the results, and...
arrays,mongodb,find,aggregate,subdocument
What you are asking for here is a little different from a standard query. In fact you are asking for where the "name" and "lastname" is found in that combination in your array two times or more to identify that document. Standard query arguments do not match "how many times"...
This seems to be a "buggy" response from mongojs which likely results from it's implementation of returning the "inserted" object as a response. The "core" driver does not do this but would either return a "ok" response or an error: var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost/test', function(err,db) { var collection =...
You can push the item into the array with the following command: db.mycollection.update({ _id: "zinfandel", "last_search.engine": { $nin: ["notwellknownengine.com"] } }, { $push: { "last_search": { "engine" : "notwellknownengine.com", "query" : "stackoveflow.com" } } }); ...
Modelling a "circle" is a valid approach by specifying a "centre" and a "radius", but finding things "within the circle" is generally straightforward if not immediately obvious: Service.collection.aggregate([ # Get the distance from the current location { "$geoNear" => { "near" => { "type" => "Point", "coordinates" => [ 1,...
The pymongo driver already has methods for importing strings as binary. Following with this example: import pymongo import bson.binary from pymonngo import MongoClient from bson.binary import Binary client = MongoClient() db = client.test db.btest.insert({ "bindata": Binary("Hello",0) }) db.btest.find_one() Which gives you: {u'_id': ObjectId('5582b33c268e1505371a5477'), u'bindata': Binary('Hello', 0)} Or from the mongo...
Your problem is how you are trying to notate the object "keys". This isn't valid for key construction in JavaScript object as the key names are literal and all characters are considered part of the name string. Notate like this instead: var update = { "rate": minRate }; update["classifierCategories."+e+".rate"] =...
db.yourcollection.insert({date_field_name:new Date()})
Try using _.extend or _.assign instead: var updated = _.assign(form, req.body); This answer by ShitalShah highlights the differences between merge and extend: Here's how extend/assign works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their...
javascript,node.js,mongodb,mongoose
Your GET request should have worked because a browser executes a GET request by default. Try the following. app.get("/database", function(req, res) { Entry.find(function(err, data) { if(err) { console.log(err); } else { console.log(data); } }); }); As far as testing your POST route is concerned, install a plugin for Google Chrome...
mongodb,meteor,collections,insert-update
Give something like this a try: // fetch the current list var list = Lists.findOne(_currentListId); // find the number of existing items and handle the case where there are none var numItems = (list.items || []).length; // the the next item key will be one more than the length var...
arrays,mongodb,aggregation-framework
This basically does what you want with some help from $cond and $ifNull: db.collection.aggregate([ { "$project": { "x": 1, "y": { "$cond": [ { "$ifNull": [ "$y.0", null] }, "$y", { "$map": { "input": ["A"], "as": "el", "in": "$y" }} ] } }} ]) So those first conditions work out...
The query needs to match on the _id (at least that is what it appears you are trying to match on). The update value for resetPasswordExpires is not a property of roles. Something like the following should work: db.users.update( { _id: ObjectId("000") }, {$set: { "resetPasswordExpires": ISODate("2015-06-20T18:04:40.014Z")} }); ...
You have to use the serverStatus database command to retrieve the version of the mongod or mongos instance you're connected to. The native node.js driver provides the Admin.serverStatus for that purpose: var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost:27017/test' var conn = MongoClient.connect(url, function(err, db) { var adminDb = db.admin();...
You need to convert the string _id to a valid Mongodb ID var mongo = require('mongodb'), BSON = mongo.BSONPure, groupid = new BSON.ObjectID(req.headers['groupid']); Cloud.find({'_id': groupid}).exec(function(err, data) { if(err){ res.status(404); res.json('group not found'); } else { // Do Stuff } }); If you use Mongoose you can convert the string to...
javascript,node.js,mongodb,iframe
I wouldn't build it entirely on Node.js I would rather use the power of the modern client-side Javascript and move some logic there with persisting some of the data coming from the server. This way I can lower the number of requests and make my script more flexible. Two libraries...
c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0
The query you need to perform uses the $elemMatch query operator. So, this query using a lambda expression var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123")); Is equivalent to this query using the FilterDefinitionBuilder: var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch( foo => foo.Bars, foobar => foobar.BarId == "123")); ...
node.js,mongodb,mongoose,mongoose-populate
In Mongoose instance methods, this is the document instance the method is being called on, so you can do this as: MainSchema.methods = { retrieveChilds: function(callback) { this.deepPopulate('childs.subject.data', callback); }, }; Then to call it: main.retrieveChilds(function(err, _main) { // _main is the same doc instance as main and is populated....
Something like this should work: 'submit form' : function(event){ event.preventDefault(); var query=document.getElementsByClassName("twilioProcessorsms")[0].value; var valueToInsert = { sms: esms }; valueToInsert[query] = { accountSID: accsid, authToken: token, phoneNumber: phno} }; ChoiceList.insert(valueToInsert); ...
javascript,node.js,mongodb,sails.js,waterline
Answering my own question! Seemed to be something goofy happening with the brew installation of MongoDB. Manually re-installing it from http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/ and then restoring my backed up database seemed to do the trick. I'd still love to know from a from a code/technical standpoint why my environment suddenly decided to...
javascript,node.js,mongodb,csv,mongoose
You can use async's eachSeries method. I assume that output is an array of users. Async's eachSeries will iterate over an array, process an item and, once the callback method is called, go to the next item in array : fs.readFile(file, function(err, data) { if (err) throw err; parse(data, function(err,...
From what I see in your terminal, I think your installation for mongoose is successful. And you are staring your application using nodemon but I think that is not installed as you are getting an error nodemon: command not found. So first you will need to install nodemon using, npm...
The amount of time it takes to add the index would depend on your hardware, but with 20206 records a simple index as you describe shouldn't take very long for most hardware. Queries fully covered by the index (i.e. where you specify A and B, or just A, but not...
Generally, the answer is don't. Don't check if a connection to MongoDB is working. You might find out that it's working right now, but the next operation might fail anyway--your sysadmin might pull your cable, the server crashes, whatever. Since you need to handle errors later in your application no...
mongodb,database-design,cassandra
If your document nesting level is not too deep, you can use User Defined Types from C* 2.1. I personally suggest to rethink your schema into more flat form like: create table profiles ( name text, name2 text, email text, username text, ts timestamp, primary key (name,name2) // compound primary...
That isn't a valid query. While you can add $orderby that way (but it's not recommended), skip and limit are not part of the document. Best thing to do is to not try to build it that way and instead let the driver build it for you. This will also...
javascript,node.js,mongodb,websocket,socket.io
In a multiplayer game, you need to do important state logic on the server, or at least do some sort of state validation on the server side. You are only noticing this "hack" because it is easy to do. You have to design your multiplayer server to be resistant against...
As stated, the closest you can get to this with your current structure is using $geoNear which is an aggregation framework operator. This has the necessary projection needs required to resolve the "match" from the sub-documents. But first a reworking of your sample without the errors: { "firstName": "firstname", "phone":...
Though this is possible to do with some real wrangling you would be best off changing the document structure to "flatten" the array entries into a single array. The main reason for this is "updates" which are not atomically supported by MongoDB with respect to updating the "inner" array due...
If you set pictures to an empty array you shouldn't have a value at index 0. var albumData = { album : 'album1', pictures : [] };...
You are looking for the $in-operator. db.collection.find({ id: { $in: { [ 1, 3 ] } }); This will get you any documents where the id-field (different from the special _id field) is 1 or 3. When you only want the values of the id field and not the whole...
node.js,mongodb,gridfs,gridfs-stream
change gfs.exist({_id: id}, function (err, found) { if (err) return handleError(err); if (!found) res.send('Error on the database looking for the file.') }); var readStream = gfs.createReadStream({ _id: id }).pipe(res); to gfs.exist({_id: id}, function (err, found) { if (err) return handleError(err); if (!found) return res.send('Error on the database looking for the...
No, you can't. The _id field is required for internal purposes in MongoDB. It is the MongoDB equivalent to a primary key in a relational database. Every document must have an unique _id field. It does not necessarily need to be an ObjectId, but it must be a value unique...
ruby-on-rails,mongodb,mongoid,nomethoderror
Apparently the way to fix this is to remove the has_many :vessels from Owner and has_many: modifications from Vessel, so that the resulting code looks like: class Owner include Mongoid::Document field :name, type: String field :uprn, type: String end class Vessel include Mongoid::Document belongs_to :owner field :name, type: String attr_accessor...
You can access fields inside an embedded document using the dot notation. Don't forget to quote the field name though. > db.collection.find() { "_id" : 1, "semester" : 1, "grades" : { "student1" : 70, "student2" : 85 } } { "_id" : 2, "semester" : 2, "grades" : {...
c#,arrays,mongodb,subset,mongodb-csharp
Use mongo Set Operator using $setIsSubset in aggregation you will get your result, check following query : db.collectionName.aggregate({ "$project": { "Name": 1, "Tags": 1, "match": { "$setIsSubset": ["$Tags", ["A", "B", "C"]] //check Tags is subset of given array in your case array is ["A","B","C"] } } }, { "$match": {...
Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...
c#,mongodb,asynchronous,parallel-processing,async-await
When you call an async method you should await the returned task, which you can only do in an async method, etc. Awaiting the task makes sure you continue execution only after the operation completed, otherwise the operation and the code after it would run concurrently. So your code should...
php,mongodb,mongodb-query,pymongo
Try to generate a MongoDate() object as follows $dateFrom = new MongoDate(strtotime("2015-06-01T00:00:00Z")); $dateTo = new MongoDate(strtotime("2015-06-03T00:00:00Z")); which you can then use in your aggregation pipeline instead of the MongoDB ISODate objects in your PHP query. /* Run the command cursor */ $result = $collection->aggregateCursor( [ [ '$match' => [ 'date'=>...
node.js,mongodb,mongoose,schema
You can try this: objectModel.find({ 'members.user_id' : {'$in' : ['asdf123lkd', 'asdf1223']} }, function(err, data) { console.log(err,data); }) ...
This should work: result <- mongo.find(Connexion, "db.col", query=list('_id' = mongo.oid.from.string("5571849db1969e0a6eb32731"))) ...
Meteor's collection API is somewhat different from that of the mongo API. find takes up to two parameters: a selector object, and an options object. options allows you to specify such things as sort, skip, limit and fields, in addition to the meteor-specific reactive and transform.
php,mongodb,aggregation,pipeline
It's true that the "standard projection" operations available to MongoDB methods such as .find() will only return at most a "single matching element" from the array to that is queried by either the positional $ operator form in the "query" portion or the $elemMatch in the "projection" portion. In order...
We can search the element value using case insensitive [...] Is there [something] similar for schema element [?] No. We may assume that JavaScript and JSON are case sensitive, and so are MongoDB queries. That being said, internally MongoDB uses BSON, and the specs say nothing about case-sensitivity of...
Generic Type of Builder should be the same as for collection's generic type. In your case collection should have type BsonDocument. var _collection = database..GetCollection<BsonDocument>("name"); var filter = Builders<BsonDocument>.Filter.Eq("_id", id); var result = _collection.Find(filter); ...
javascript,jquery,mongodb,google-maps,google-maps-api-3
You can first set the visibility of the div which contains map to hidden; then listen to the first tilesloaded event, and set the visibility back to visible. Doing this the Maps should only pop up after all it tiles is loaded (so no gray screen) Here is a quick...
javascript,json,mongodb,meteor
JS Template.test.helpers({ itemsArray: function(){ // This would normally be the result of your Mongo query var itemsArray = [ { "_id": "SXTJBs7QLXoyMFGpK", "Brand": "Nike", "Material": "Cooton", "Price": "67484", "ComboId": "y23", "Color": "White", "LaunchDate": "08/02/2015", "DiscountActiveDate": "08/03/2015", "DiscountInactiveDate": "08/04/2015", "Category": "Sport", "ProductSubCategory": "trackpant", "Status": "Pending", "TemplateID": "557fc7d06ecb48d38a67a380" }, { "_id": "IGJHihljiUYG6787y",...