question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I am evaluating what might be the best migration option. Currently, I am on a sharded MySQL (horizontal partition), with most of my data stored in JSON blobs. I do not have any complex SQL queries (already migrated away after since I partitioned my db). Right now, it seems like both MongoDB and Cassandra would be likel...
Lots of reads in every query, fewer regular writes Both databases perform well on reads where the hot data set fits in memory. Both also emphasize join-less data models (and encourage denormalization instead), and both provide indexes on documents or rows, although MongoDB's indexes are currently more flexible. Cassan...
MongoDB
2,892,729
764
I'm looking for an operator, which allows me to check, if the value of a field contains a certain string. Something like: db.users.findOne({$contains:{"username":"son"}}) Is that possible?
You can do it with the following code. db.users.findOne({"username" : {$regex : "son"}});
MongoDB
10,610,131
749
If I have this schema... person = { name : String, favoriteFoods : Array } ... where the favoriteFoods array is populated with strings. How can I find all persons that have "sushi" as their favorite food using mongoose? I was hoping for something along the lines of: PersonModel.find({ favoriteFoods : { $contai...
As favouriteFoods is a simple array of strings, you can just query that field directly: PersonModel.find({ favouriteFoods: "sushi" }, ...); // favouriteFoods contains "sushi" But I'd also recommend making the string array explicit in your schema: person = { name : String, favouriteFoods : [String] } The relev...
MongoDB
18,148,166
722
I am stuck between these two NoSQL databases. In my project, I will be creating a database within a database. For example, I need a solution to create dynamic tables. So users can create tables with columns and rows. I think either MongoDB or CouchDB will be good for this, but I am not sure which one. I will also need ...
Of C, A & P (Consistency, Availability & Partition tolerance) which 2 are more important to you? Quick reference, the Visual Guide To NoSQL Systems MongodB : Consistency and Partition Tolerance CouchDB : Availability and Partition Tolerance A blog post, Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Mem...
MongoDB
12,437,790
692
I can't find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the last N records in mongodb? Edit: also I want the returned result ordered from less recent to most recent, not the reverse.
If I understand your question, you need to sort in ascending order. Assuming you have some id or date field called "x" you would do ... .sort() db.foo.find().sort({x:1}); The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.) If you use the auto created _id field it has a date em...
MongoDB
4,421,207
692
I want to design a question structure with some comments. Which relationship should I use for comments: embed or reference? A question with some comments, like stackoverflow, would have a structure like this: Question title = 'aaa' content = 'bbb' comments = ??? At first, I thought of using embedded commen...
This is more an art than a science. The Mongo Documentation on Schemas is a good reference, but here are some things to consider: Put as much in as possible The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because Mong...
MongoDB
5,373,198
638
There's a typo in my MongoDB database name and I'm looking to rename the database. I can copy and delete like so... db.copyDatabase('old_name', 'new_name'); use old_name db.dropDatabase(); Is there a command to rename a database?
You could do this, if you're using MongoDB < 4.2 (ref): db.copyDatabase("db_to_rename","db_renamed","localhost") use db_to_rename db.dropDatabase(); Editorial Note: this is the same approach used in the question itself but has proven useful to others regardless.
MongoDB
9,201,832
601
Is there a way to tell Mongo to pretty print output? Currently, everything is output to a single line and it's difficult to read, especially with nested arrays and documents.
(note: this is answer to original version of the question, which did not have requirements for "default") You can ask it to be pretty. db.collection.find().pretty()
MongoDB
9,146,123
575
I've been playing around storing tweets inside mongodb, each object looks like this: { "_id" : ObjectId("4c02c58de500fe1be1000005"), "contributors" : null, "text" : "Hello world", "user" : { "following" : null, "followers_count" : 5, "utc_offset" : null, "location" : "", "profile_text_color" : "0000...
Querying for a Date Range (Specific Month or Day) in the MongoDB Cookbook has a very good explanation on the matter, but below is something I tried out myself and it seems to work. items.save({ name: "example", created_at: ISODate("2010-04-30T00:00:00.000Z") }) items.find({ created_at: { $gte: ISODa...
MongoDB
2,943,222
560
I am using my new mac for the first time today. I am following the get started guide on the mongodb.org up until the step where one creates the /data/db directory. btw, I used the homebrew route. So I open a terminal, and I think I am at what you called the Home Directory, for when I do "ls", I see folders of Desktop ...
You created the directory in the wrong place /data/db means that it's directly under the '/' root directory, whereas you created 'data/db' (without the leading /) probably just inside another directory, such as the '/root' homedirectory. You need to create this directory as root Either you need to use sudo , e.g. sudo ...
MongoDB
7,948,789
550
In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like: UPDATE Person SET Name = FirstName + ' ' + LastName And the MongoDB pseudo-code would be: db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
The best way to do this is in version 4.2+ which allows using the aggregation pipeline in the update document and the updateOne, updateMany, or update(deprecated in most if not all languages drivers) collection methods. MongoDB 4.2+ Version 4.2 also introduced the $set pipeline stage operator, which is an alias for $a...
MongoDB
3,974,985
545
I'm doing development on MongoDB. For totally non-evil purposes, I sometimes want to blow away everything in a database—that is, to delete every single collection, and whatever else might be lying around, and start from scratch. Is there a single line of code that will let me do this? Bonus points for giving both a Mon...
In the mongo shell: use [database]; db.dropDatabase(); And to remove the users: db.dropAllUsers();
MongoDB
3,366,397
539
We offer a platform for video- and audio-clips, photos and vector-grafics. We started with MySQL as the database backend and recently included MongoDB for storing all meta-information of the files, because MongoDB better fits the requirements. For example: photos may have Exif information, videos may have audio-tracks ...
In NoSQL: If Only It Was That Easy, the author writes about MongoDB: MongoDB is not a key/value store, it’s quite a bit more. It’s definitely not a RDBMS either. I haven’t used MongoDB in production, but I have used it a little building a test app and it is a very cool piece of kit. It seems to be very performant and ...
MongoDB
1,476,295
531
Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :) Here's the deal: I have a contact schema and model (shortened properties): var mongoose = require('mongoose'), Schema = mongoose.Schema; var mongooseTypes = requ...
Mongoose now supports this natively with findOneAndUpdate (calls MongoDB findAndModify). The upsert = true option creates the object if it doesn't exist. defaults to false. var query = {'username': req.user.username}; req.newData.username = req.user.username; MyModel.findOneAndUpdate(query, req.newData, {upsert: true}...
MongoDB
7,267,102
510
I want to execute mongo commands in shell script, e.g. in a script test.sh: #!/bin/sh mongo myDbName db.mycollection.findOne() show collections When I execute this script via ./test.sh, then the connection to MongoDB is established, but the following commands are not executed. How to execute other commands through she...
You can also evaluate a command using the --eval flag, if it is just a single command. mongo --eval "printjson(db.serverStatus())" Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an envir...
MongoDB
4,837,673
496
{ name: 'book', tags: { words: ['abc','123'], lat: 33, long: 22 } } Suppose this is a document. How do I remove "words" completely from all the documents in this collection? I want all documents to be without "words": { name: 'book', tags: { lat: 33, l...
Try this: If your collection was 'example' db.example.update({}, {$unset: {words:1}}, false, true); Refer this: http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset UPDATE: The above link no longer covers '$unset'ing. Be sure to add {multi: true} if you want to remove this field from all of the documents in ...
MongoDB
6,851,933
487
Suppose you have the following documents in my collection: { "_id":ObjectId("562e7c594c12942f08fe4192"), "shapes":[ { "shape":"square", "color":"blue" }, { "shape":"circle", "color":"red" } ] }, { "_id":ObjectId("562e7c594c12942f08fe4193...
MongoDB 2.2's new $elemMatch projection operator provides another way to alter the returned document to contain only the first matched shapes element: db.test.find( {"shapes.color": "red"}, {_id: 0, shapes: {$elemMatch: {color: "red"}}}); Returns: {"shapes" : [{"shape": "circle", "color": "red"}]} In 2.2 you...
MongoDB
3,985,214
485
I was wondering if anyone can tell me if MongoDB or CouchDB are ready for a production environment. I'm now looking at these storage solutions (I'm favouring MongoDB at the moment), however these projects are quite young and so I foresee that I'm going to have to work quite hard to convince my manager that we should ...
I'm the CTO of 10gen (developers of MongoDB) so I'm a bit biased, but I also manage a few sites that are using MongoDB in production. businessinsider has been using mongo in production for over a year now. They are using it for everything from users and blog posts, to every image on the site. shopwiki is using it for ...
MongoDB
895,762
485
How can I add a new field to every document in an existent collection? I know how to update an existing document's field but not how to add a new field to every document in a collection. How can I do this in the mongo shell?
Same as the updating existing collection field, $set will add a new fields if the specified field does not exist. Check out this example: > db.foo.find() > db.foo.insert({"test":"a"}) > db.foo.find() { "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" } > item = db.foo.findOne() { "_id" : ObjectId("4e93037bbf6...
MongoDB
7,714,216
475
What I want is not a comparison between Redis and MongoDB. I know they are different; the performance and the API is totally different. Redis is very fast, but the API is very 'atomic'. MongoDB will eat more resources, but the API is very very easy to use, and I am very happy with it. They're both awesome, and I want t...
I would say, it depends on kind of dev team you are and your application needs. For example, if you require a lot of querying, that mostly means it would be more work for your developers to use Redis, where your data might be stored in variety of specialized data structures, customized for each type of object for effic...
MongoDB
5,400,163
466
I want to set up user name & password authentication for my MongoDB instance, so that any remote access will ask for the user name & password. I tried the tutorial from the MongoDB site and did following: use admin db.addUser('theadmin', '12345'); db.auth('theadmin','12345'); After that, I exited and ran mongo again....
Wow so many complicated/confusing answers here. This is as of v3.4. Short answer. Start MongoDB without access control (/data/db or where your db is). mongod --dbpath /data/db Connect to the instance. mongo Create the user. use some_db db.createUser( { user: "myNormalUser", pwd: "xyz123", roles: [ { ...
MongoDB
4,881,208
446
I'm using Mongoose version 3 with MongoDB version 2.2. I've noticed a __v field has started appearing in my MongoDB documents. Is it something to do with versioning? How is it used?
From here: The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is __v. If this conflicts with your application you can configure as such: new Schema({..},...
MongoDB
12,495,891
438
Below is my code var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var Cat = mongoose.model('Cat', { name: String, age: {type: Number, default: 20}, create: {type: Date, default: Date.now} }); Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){ if...
Why this happens? The default is to return the original, unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: an object with the new property set to true. From the mongoose docs: Query#findOneAndUpdate Model.findOneAndUpdate(conditions, update, options, (er...
MongoDB
32,811,510
432
I've found this question answered for C# and Perl, but not in the native interface. I thought this would work: db.theColl.find( { _id: ObjectId("4ecbe7f9e8c1c9092c000027") } ) The query returned no results. I found the 4ecbe7f9e8c1c9092c000027 by doing db.theColl.find() and grabbing an ObjectId. There are several thou...
Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact. Documentation is here > db.test.insertOne({x: 1}) > db.test.find() // no criteria { "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : ...
MongoDB
8,233,014
409
Example: > db.stuff.save({"foo":"bar"}); > db.stuff.find({"foo":"bar"}).count(); 1 > db.stuff.find({"foo":"BAR"}).count(); 0
You could use a regex. In your example that would be: db.stuff.find( { foo: /^bar$/i } ); I must say, though, maybe you could just downcase (or upcase) the value on the way in rather than incurring the extra cost every time you find it. Obviously this wont work for people's names and such, but maybe use-cases like tag...
MongoDB
1,863,399
405
I have been very excited about MongoDb and have been testing it lately. I had a table called posts in MySQL with about 20 million records indexed only on a field called 'id'. I wanted to compare speed with MongoDB and I ran a test which would get and print 15 records randomly from our huge databases. I ran the query ab...
MongoDB is not magically faster. If you store the same data, organised in basically the same fashion, and access it exactly the same way, then you really shouldn't expect your results to be wildly different. After all, MySQL and MongoDB are both GPL, so if Mongo had some magically better IO code in it, then the MySQL t...
MongoDB
9,702,643
382
I'd like to get the names of all the keys in a MongoDB collection. For example, from this: db.things.insert( { type : ['dog', 'cat'] } ); db.things.insert( { egg : ['cat'] } ); db.things.insert( { type : [] } ); db.things.insert( { hello : [] } ); I'd like to get the unique keys: type, egg, hello
You could do this with MapReduce: mr = db.runCommand({ "mapreduce" : "my_collection", "map" : function() { for (var key in this) { emit(key, null); } }, "reduce" : function(key, stuff) { return null; }, "out": "my_collection" + "_keys" }) Then run distinct on the resulting collection so as to find all t...
MongoDB
2,298,870
378
Following is my user schema in user.js model - var userSchema = new mongoose.Schema({ local: { name: { type: String }, email : { type: String, require: true, unique: true }, password: { type: String, require:true }, }, facebook: { id : { type: String }, toke...
The error message is saying that there's already a record with null as the email. In other words, you already have a user without an email address. The relevant documentation for this: If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Beca...
MongoDB
24,430,220
371
I have an array of _ids and I want to get all docs accordingly, what's the best way to do it ? Something like ... // doesn't work ... of course ... model.find({ '_id' : [ '4ed3ede8844f0f351100000c', '4ed3f117a844e0471100000d', '4ed3f18132f50c491100000e' ] }, function(err, docs){ co...
The find function in mongoose is a full query to mongoDB. This means you can use the handy mongoDB $in clause, which works just like the SQL version of the same. model.find({ '_id': { $in: [ mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'), mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), ...
MongoDB
8,303,900
362
I'm using the node-mongodb-native driver with MongoDB to write a website. I have some questions about how to manage connections: Is it enough using only one MongoDB connection for all requests? Are there any performance issues? If not, can I setup a global connection to use in the whole application? If not, is it good...
The primary committer to node-mongodb-native says: You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool. So, to answer your question directly, reuse the db object that results from MongoClient.connect(...
MongoDB
10,656,574
361
I am playing around with MongoDB trying to figure out how to do a simple SELECT province, COUNT(*) FROM contest GROUP BY province But I can't seem to figure it out using the aggregate function. I can do it using some really weird group syntax db.user.group({ "key": { "province": true }, "initial": ...
This would be the easier way to do it using aggregate: db.contest.aggregate([ {"$group" : {_id:"$province", count:{$sum:1}}} ])
MongoDB
23,116,330
352
I know how to list all collections in a particular database, but how do I list all available databases in MongoDB shell?
Listing all the databases in mongoDB console is using the command show dbs. For more information on mongo shell commands, refer the MongoDB Shell (mongosh) documentation.
MongoDB
25,947,929
349
I have a data like this in mongodb { "latitude" : "", "longitude" : "", "course" : "", "battery" : "0", "imei" : "0", "altitude" : "F:3.82V", "mcc" : "07", "mnc" : "007B", "lac" : "2A83", "_id" : ObjectId("4f0eb2c406ab6a9d4d000003"), "createdAt" : ISODate("2012-01-...
You probably want to make a range query, for example, all items created after a given date: db.gpsdatas.find({"createdAt" : { $gte : new ISODate("2012-01-12T20:15:31Z") }}); I'm using $gte (greater than or equals), because this is often used for date-only queries, where the time component is 00:00:00. If you really wa...
MongoDB
8,835,757
344
Suppose the mongodb document(table) 'users' is { _id: 1, name: { first: 'John', last: 'Backus' }, birth: new Date('Dec 03, 1924'), death: new Date('Mar 17, 2007'), contribs: ['Fortran', 'ALGOL', 'Backus-Naur Form', 'FP'], awards: [ { award: 'National Medal...
The right way is: db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}}) $elemMatch allows you to match more than one component within the same array element. Without $elemMatch mongo will look for users with National Medal in some year and some award in the year 1975, but not for users with Nation...
MongoDB
14,040,562
339
Can you share your thoughts how would you implement data versioning in MongoDB. (I've asked similar question regarding Cassandra. If you have any thoughts which db is better for that please share) Suppose that I need to version records in an simple address book. (Address book records are stored as flat json objects). I...
The first big question when diving in to this is "how do you want to store changesets"? Diffs? Whole record copies? My personal approach would be to store diffs. Because the display of these diffs is really a special action, I would put the diffs in a different "history" collection. I would use the different collecti...
MongoDB
4,185,105
337
If you have subdocument arrays, Mongoose automatically creates ids for each one. Example: { _id: "mainId" subDocArray: [ { _id: "unwantedId", field: "value" }, { _id: "unwantedId", field: "value" } ] } Is there a way to tell Mongoose to not create ids...
It's simple, you can define this in the subschema : var mongoose = require("mongoose"); var subSchema = mongoose.Schema({ // your subschema content }, { _id : false }); var schema = mongoose.Schema({ // schema content subSchemaCollection : [subSchema] }); var model = mongoose.model('tablename', schema); ...
MongoDB
17,254,008
336
Basically I have a mongodb collection called 'people' whose schema is as follows: people: { name: String, friends: [{firstName: String, lastName: String}] } Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends arra...
Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' }; There are two options you have: Update the model in-memory, and save (plain javascript array.push): person.friends.push(friend); person.save(done); or PersonModel.update( { _id: person._id }, { $push: { friends: friend } }, done ); I alwa...
MongoDB
33,049,707
331
I am trying to add authorization to my MongoDB. I am doing all this on Linux with MongoDB 2.6.1. My mongod.conf file is in the old compatibility format (this is how it came with the installation). 1) I created admin user as described here in (3) http://docs.mongodb.org/manual/tutorial/add-user-administrator/ 2) I t...
I was also scratching my head around the same issue, and everything worked after I set the role to be root when adding the first admin user. use admin db.createUser( { user: 'admin', pwd: 'password', roles: [ { role: 'root', db: 'admin' } ] } ); exit; If you have already created the admin user, you can...
MongoDB
23,943,651
330
I am writing a webapp with Node.js and mongoose. How can I paginate the results I get from a .find() call? I would like a functionality comparable to "LIMIT 50,100" in SQL.
I'm am very disappointed by the accepted answers in this question. This will not scale. If you read the fine print on cursor.skip( ): The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to r...
MongoDB
5,539,955
328
db.foo.find().limit(300) won't do it. It still prints out only 20 documents. db.foo.find().toArray() db.foo.find().forEach(printjson) will both print out very expanded view of each document instead of the 1-line version for find():
DBQuery.shellBatchSize = 300 MongoDB Docs - Configure the mongo Shell - Change the mongo Shell Batch Size
MongoDB
3,705,517
322
I have a basic Node.js app that I am trying to get off the ground using the Express framework. I have a views folder where I have an index.html file. But I receive the following error when loading the web page: Error: Cannot find module 'html' Below is my code. var express = require('express'); var app = express.creat...
You can have jade include a plain HTML page: in views/index.jade include plain.html in views/plain.html <!DOCTYPE html> ... and app.js can still just render jade: res.render(index)
MongoDB
4,529,586
321
I have a node.js application that pulls some data and sticks it into an object, like this: var results = new Object(); User.findOne(query, function(err, u) { results.userId = u._id; } When I do an if/then based on that stored ID, the comparison is never true: if (results.userId == AnotherMongoDocument._id) { ...
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals() method. With your example, results.userId.equals(AnotherMongoDocument._id). The ObjectID type also has a toString() method, if you wish to store a stringified version of the ObjectID in JSON format...
MongoDB
11,637,353
312
Is there a simple way to do this?
The best way is to do a mongodump then mongorestore. You can select the collection via: mongodump -d some_database -c some_collection [Optionally, zip the dump (zip some_database.zip some_database/* -r) and scp it elsewhere] Then restore it: mongorestore -d some_other_db -c some_or_other_collection dump/some_collectio...
MongoDB
11,554,762
309
I have a problem when querying mongoDB with nested objects notation: db.messages.find( { headers : { From: "reservations@marriott.com" } } ).count() 0 db.messages.find( { 'headers.From': "reservations@marriott.com" } ).count() 5 I can't see what I am doing wrong. I am expecting nested object notation to return the sa...
db.messages.find( { headers : { From: "reservations@marriott.com" } } ) This queries for documents where headers equals { From: ... }, i.e. contains no other fields. db.messages.find( { 'headers.From': "reservations@marriott.com" } ) This only looks at the headers.From field, not affected by other fields contained in...
MongoDB
16,002,659
303
Assuming I have a collection in MongoDB with 5000 records, each containing something similar to: { "occupation":"Doctor", "name": { "first":"Jimmy", "additional":"Smith" } Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not...
You can use: db.foo.update({}, { $rename: { "name.additional": "name.last" } }, false, true); Or to just update the docs which contain the property: db.foo.update({ "name.additional": { $exists: true } }, { $rename: { "name.additional": "name.last" } }, false, true); Th...
MongoDB
9,254,351
299
Is there a set of preferred naming conventions for MongoDB entitites such as databases, collections, field names? I was thinking along these lines: Databases: consist of the purpose (word in singular) and end with “db” – all lower case: imagedb, resumedb, memberdb, etc. Collections: plural in lower case: images, resum...
Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true. I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural... MongoDB speaks JavaScript, so utilize J...
MongoDB
5,916,080
293
With the NoSQL movement growing based on document-based databases, I've looked at MongoDB lately. I have noticed a striking similarity with how to treat items as "Documents", just like Lucene does (and users of Solr). So, the question: Why would you want to use NoSQL (MongoDB, Cassandra, CouchDB, etc) over Lucene (or ...
This is a great question, something I have pondered over quite a bit. I will summarize my lessons learned: You can easily use Lucene/Solr in lieu of MongoDB for pretty much all situations, but not vice versa. Grant Ingersoll's post sums it up here. MongoDB etc. seem to serve a purpose where there is no requirement of ...
MongoDB
3,215,029
284
Given this document saved in MongoDB { _id : ..., some_key: { param1 : "val1", param2 : "val2", param3 : "val3" } } An object with new information on param2 and param3 from the outside world needs to be saved var new_info = { param2 : "val2_new", param3 : "val3_new" }; I wan...
I solved it with my own function. If you want to update specified field in document you need to address it clearly. Example: { _id : ..., some_key: { param1 : "val1", param2 : "val2", param3 : "val3" } } If you want to update param2 only, it's wrong to do: db.collection.update( { ...
MongoDB
10,290,621
283
> db.data.update({'name': 'zero'}, {'$set': {'value': 0}}) > db.data.findOne({'name': 'zero}) {'name': 'zero', 'value': 0.0} How do I get Mongo to insert an integer? Thank you
db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}}) You can also use NumberLong.
MongoDB
8,218,484
280
I wanted to use the mongodb database, but I noticed that there are two different databases with either their own website and installation methods: mongodb and mongoose. So I came up asking myself this question: "Which one do I use?". So in order to answer this question I ask the community if you could explain what are ...
I assume you already know that MongoDB is a NoSQL database system which stores data in the form of BSON documents. Your question, however is about the packages for Node.js. In terms of Node.js, mongodb is the native driver for interacting with a mongodb instance and mongoose is an Object modeling tool for MongoDB. mon...
MongoDB
28,712,248
263
I have a collected named foo hypothetically. Each instance of foo has a field called lastLookedAt which is a UNIX timestamp since epoch. I'd like to be able to go through the MongoDB client and set that timestamp for all existing documents (about 20,000 of them) to the current timestamp. What's the best way of handling...
Regardless of the version, for your example, the <update> is: { $set: { lastLookedAt: Date.now() / 1000 } } However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB cli...
MongoDB
9,038,547
262
I am not a database expert and have no formal computer science background, so bear with me. I want to know the kinds of real world negative things that can happen if you use an old MongoDB version prior to v4, which were not ACID compliant. This applies to any ACID noncompliant database. I understand that MongoDB can...
It's actually not correct that MongoDB is not ACID-compliant. On the contrary, MongoDB is ACID-compilant at the document level. Any update to a single document is Atomic: it either fully completes or it does not Consistent: no reader will see a "partially applied" update Isolated: again, no reader will see a "dirt...
MongoDB
7,149,890
257
Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as objectId("blah").
You can do it like so: var mongoose = require('mongoose'); var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
MongoDB
6,578,178
257
Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in everytime new MyModel() is called? The created_at field would be a date and only added when a document is created. The updated_at field would be updated with new date whenever save() is called on a document. I ha...
UPDATE: (5 years later) Note: If you decide to use Kappa Architecture (Event Sourcing + CQRS), then you do not need updated date at all. Since your data is an immutable, append-only event log, you only ever need event created date. Similar to the Lambda Architecture, described below. Then your application state is a p...
MongoDB
12,669,615
255
I have a Mongo document which holds an array of elements. I'd like to reset the .handled attribute of all objects in the array where .profile = XX. The document is in the following form: { "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), "user_id": "714638ba-2e08-2168-2b99-00002f3d43c0", "events": [{ ...
With the release of MongoDB 3.6 ( and available in the development branch from MongoDB 3.5.12 ) you can now update multiple array elements in a single request. This uses the filtered positional $[<identifier>] update operator syntax introduced in this version: db.collection.update( { "events.profile":10 }, { "$set"...
MongoDB
4,669,178
247
Assume we have the following collection, which I have few questions about: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { "item_name" : "my_item_one", "price" : 20 }, { ...
For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like: db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , {$inc : {"items.$.price"...
MongoDB
10,522,347
246
I don't seem to be able to get even the most basic date query to work in MongoDB. With a document that looks something like this: { "_id" : "foobar/201310", "ap" : "foobar", "dt" : ISODate("2013-10-01T00:00:00.000Z"), "tl" : 375439 } And a query that looks like this: { "dt" : { "$gte" : ...
Although $date is a part of MongoDB Extended JSON and that's what you get as default with mongoexport, I don't think you can really use it as a part of the query. If try exact search with $date like below: db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}}) you'll get the error: error: { "$err" : "invalid operato...
MongoDB
19,819,870
242
What command should I use to create a MongoDB dump of my database?
To dump your database for backup you call this command on your terminal mongodump --db database_name --collection collection_name To import your backup file to mongodb you can use the following command on your terminal mongorestore --db database_name path_to_bson_file
MongoDB
4,880,874
242
I have mongoDB 3.2 installed locally for Windows 7. I would like to find out its specific version (like is it 3.2.1, or 3.2.3 or...). How could I find it? If I open the database shell (mongo.exe), I can see it outputs: MongoDB shell version: 3.2.0 But that's just the shell version, and I'm not sure whether it's the s...
Just run your console and type: db.version() https://docs.mongodb.com/manual/reference/method/db.version/
MongoDB
38,160,412
241
How would I find duplicate fields in a mongo collection. I'd like to check if any of the "name" fields are duplicates. { "name" : "ksqn291", "__v" : 0, "_id" : ObjectId("540f346c3e7fc1054ffa7086"), "channel" : "Sales" } Many thanks!
Use aggregation on name and get name with count > 1: db.collection.aggregate([ {"$group" : { "_id": "$name", "count": { "$sum": 1 } } }, {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, {"$project": {"name" : "$_id", "_id" : 0} } ]); To sort the results by most to least duplicates: db.colle...
MongoDB
26,984,799
239
How can I set up MongoDB so it can run as a Windows service?
After trying for several hours, I finally did it. Make sure: you added the <MONGODB_PATH>\bin directory to the system variable PATH run command prompt as administrator Steps: step 1: execute this command: D:\mongodb\bin>mongod --remove Step 2: execute this command after opening command prompt as administrator: D:\m...
MongoDB
2,438,055
230
I am coming from riak and redis where I never had an issue with this services starting, or to interact. This is a pervasive problem with mongo and am rather clueless. Restarting does not help.I am new to mongo. mongo MongoDB shell version: 2.2.1 connecting to: test Fri Nov 9 16:44:06 Error: couldn't connect to serve...
Normally this caused because you didn't start mongod process before you try starting mongo shell. Start mongod server mongod Open another terminal window Start mongo shell mongo
MongoDB
13,312,358
227
I'm creating a sort of background job queue system with MongoDB as the data store. How can I "listen" for inserts to a MongoDB collection before spawning workers to process the job? Do I need to poll every few seconds to see if there are any changes from last time, or is there a way my script can wait for inserts to oc...
What you are thinking of sounds a lot like triggers. MongoDB does not have any support for triggers, however some people have "rolled their own" using some tricks. The key here is the oplog. When you run MongoDB in a Replica Set, all of the MongoDB actions are logged to an operations log (known as the oplog). The oplog...
MongoDB
9,691,316
227
Here is array structure contact: { phone: [ { number: "+1786543589455", place: "New Jersey", createdAt: "" } { number: "+1986543589455", place: "Houston", createdAt: "" } ] } Here I only know the mongo id(_...
Try the following query: collection.update( { _id: id }, { $pull: { 'contact.phone': { number: '+1786543589455' } } } ); It will find document with the given _id and remove the phone +1786543589455 from its contact.phone array. You can use $unset to unset the value in the array (set it to null), but not to remove ...
MongoDB
16,959,099
223
Is it possible for the same exact Mongo ObjectId to be generated for a document in two different collections? I realize that it's definitely very unlikely, but is it possible? Without getting too specific, the reason I ask is that with an application that I'm working on we show public profiles of elected officials w...
Short Answer Just to add a direct response to your initial question: YES, if you use BSON Object ID generation, then for most drivers the IDs are almost certainly going to be unique across collections. See below for what "almost certainly" means. Long Answer The BSON Object ID's generated by Mongo DB drivers are highly...
MongoDB
4,677,237
223
I have a JSON file consisting of about 2000 records. Each record which will correspond to a document in the mongo database is formatted as follows: {jobID:"2597401", account:"XXXXX", user:"YYYYY", pkgT:{"pgi/7.2-5":{libA:["libpgc.so"],flavor:["default"]}}, startEpoch:"1338497979", runTime:"1022", execType:"user:b...
I was able to fix the error using the following query: mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray Hopefully this is helpful to someone.
MongoDB
15,171,622
222
How can I store images in a MongoDB database rather than just text? Can I create an array of images in a MongoDB database? Will it be possible to do the same for videos?
Please see the GridFS docs for details on storing such binary data. Support for your specific language should be linked to at the bottom of the screen.
MongoDB
4,796,914
222
It's widely mentioned that Redis is "Blazing Fast" and mongoDB is fast too. But, I'm having trouble finding actual numbers comparing the results of the two. Given similar configurations, features and operations (and maybe showing how the factor changes with different configurations and operations), etc, is Redis 10x fa...
Rough results from the following benchmark: 2x write, 3x read. Here's a simple benchmark in python you can adapt to your purposes, I was looking at how well each would perform simply setting/retrieving values: #!/usr/bin/env python2.7 import sys, time from pymongo import Connection import redis # connect to redis & mo...
MongoDB
5,252,577
220
let's say I run this query in Mongoose: Room.find({}, (err,docs) => { }).sort({date:-1}); This doesn't work!
Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date field can be done in any of the following ways: Room.find({}).sort('-date').exec((err, docs) => { ... }); Room.find({}).sort({date: -1}).exec(...
MongoDB
5,825,520
219
I'd like to generate a MongoDB ObjectId with Mongoose. Is there a way to access the ObjectId constructor from Mongoose? This question is about generating a new ObjectId from scratch. The generated ID is a brand new universally unique ID. Another question asks about creating an ObjectId from an existing string represen...
You can find the ObjectId constructor on require('mongoose').Types. Here is an example: var mongoose = require('mongoose'); var id = mongoose.Types.ObjectId(); id is a newly generated ObjectId. Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new: var id = new mongoose.Types.ObjectId(...
MongoDB
17,899,750
218
Not Sure what I'm doing wrong, here is my check.js var db = mongoose.createConnection('localhost', 'event-db'); db.on('error', console.error.bind(console, 'connection error:')); var a1= db.once('open',function(){ var user = mongoose.model('users',{ name:String, email:String, password:String, ...
Another reason you might get this error is if you use the same model in different files but your require path has a different case. For example, in my situation I had require('./models/User') in one file, and then in another file where I needed access to the User model, I had require('./models/user'). I guess the looku...
MongoDB
19,051,041
214
I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows: import pymongo from pymongo import Connection connection = Connection() db = connection.myDB print db.posts.count() for post in db.posts.find({}, {'entities.u...
.sort(), in pymongo, takes key and direction as parameters. So if you want to sort by, let's say, id then you should .sort("_id", 1) For multiple fields: .sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
MongoDB
8,109,122
214
I've seen using strings, integer timestamps and mongo datetime objects.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects. > db.test.insert({date: ISODate()}) > db.test.insert({date: new Date()}) > db.test.find() { "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") } { "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10...
MongoDB
3,778,428
213
I saw the following code in this commit for MongoDB's Java Connection driver, and it appears at first to be a joke of some sort. What does the following code do? if (!((_ok) ? true : (Math.random() > 0.1))) { return res; } (EDIT: the code has been updated since posting this question)
After inspecting the history of that line, my main conclusion is that there has been some incompetent programming at work. That line is gratuitously convoluted. The general form a? true : b for boolean a, b is equivalent to the simple a || b The surrounding negation and excessive parentheses convolute things further...
MongoDB
16,833,100
212
So I'm attempting to find all records who have a field set and isn't null. I try using $exists, however according to the MongoDB documentation, this query will return fields who equal null. $exists does match documents that contain the field that stores the null value. So I'm now assuming I'll have to do something li...
Use $ne (for "not equal") db.collection.find({ "fieldToCheck": { $ne: null } })
MongoDB
19,868,016
210
The question is as basic as it is simple... How do you log all queries in a "tail"able log file in mongodb? I have tried: setting the profiling level setting the slow ms parameter starting mongod with the -vv option The /var/log/mongodb/mongodb.log keeps showing just the current number of active connections...
You can log all queries: $ mongo MongoDB shell version: 2.4.9 connecting to: test > use myDb switched to db myDb > db.getProfilingLevel() 0 > db.setProfilingLevel(2) { "was" : 0, "slowms" : 1, "ok" : 1 } > db.getProfilingLevel() 2 > db.system.profile.find().pretty() Source: http://docs.mongodb.org/manual/reference/met...
MongoDB
15,204,341
210
I am just starting out with MongoDB and one of the things that I have noticed is that it uses BSON to store data internally. However the documentation is not exactly clear on what BSON is and how it is used in MongoDB. Can someone explain it to me, please?
BSON is the binary encoding of JSON-like documents that MongoDB uses when storing documents in collections. It adds support for data types like Date and binary that aren't supported in JSON. In practice, you don't have to know much about BSON when working with MongoDB, you just need to use the native types of your lang...
MongoDB
12,438,280
210
CSV file with contact information: Name,Address,City,State,ZIP Jane Doe,123 Main St,Whereverville,CA,90210 John Doe,555 Broadway Ave,New York,NY,10010 Running this doesn't add documents to the database: $ mongoimport -d mydb -c things --type csv --file locations.csv --headerline Trace says imported 1 objects, bu...
Your example worked for me with MongoDB 1.6.3 and 1.7.3. Example below was for 1.7.3. Are you using an older version of MongoDB? $ cat > locations.csv Name,Address,City,State,ZIP Jane Doe,123 Main St,Whereverville,CA,90210 John Doe,555 Broadway Ave,New York,NY,10010 ctrl-d $ mongoimport -d mydb -c things --type csv --...
MongoDB
4,686,500
210
When sending a request to /customers/41224d776a326fb40f000001 and a document with _id 41224d776a326fb40f000001 does not exist, doc is null and I'm returning a 404: Controller.prototype.show = function(id, res) { this.model.findById(id, function(err, doc) { if (err) { throw err; } if (!do...
Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc. This is an ObjectId but "foo" is not a valid ObjectId so the cast fails. This doesn't happen with 41224d776a326fb40f000001 because that string is a valid ObjectId. One way to resol...
MongoDB
14,940,660
208
My host came with a mongodb instance and there is no /db directory so now I am wondering what I can do to find out where the data is actually being stored.
mongod defaults the database location to /data/db/. If you run ps -xa | grep mongod and you don't see a --dbpath which explicitly tells mongod to look at that parameter for the db location and you don't have a dbpath in your mongodb.conf, then the default location will be: /data/db/ and you should look there.
MongoDB
7,247,474
206
I'm trying to select only a specific field with exports.someValue = function(req, res, next) { //query with mongoose var query = dbSchemas.SomeValue.find({}).select('name'); query.exec(function (err, someValue) { if (err) return next(err); res.send(someValue); }); }; But in my json res...
The _id field is always present unless you explicitly exclude it. Do so using the - syntax: exports.someValue = function(req, res, next) { //query with mongoose var query = dbSchemas.SomeValue.find({}).select('name -_id'); query.exec(function (err, someValue) { if (err) return next(err); re...
MongoDB
24,348,437
205
This question is about making an architectural choice prior to delving into the details of experimentation and implementation. It's about the suitability, in scalability and performance terms, of elasticsearch v.s. MongoDB, for a somewhat specific purpose. Hypothetically both store data objects that have fields and va...
First off, there is an important distinction to make here: MongoDB is a general purpose database, Elasticsearch is a distributed text search engine backed by Lucene. People have been talking about using Elasticsearch as a general purpose database but know that it was not its' original design. I think that general purpo...
MongoDB
12,723,239
205
Is it possible to query for a specific date ? I found in the mongo Cookbook that we can do it for a range Querying for a Date Range Like that : db.posts.find({"created_on": {"$gte": start, "$lt": end}}) But is it possible for a specific date ? This doesn't work : db.posts.find({"created_on": new Date(2012, 7, 14) })
That should work if the dates you saved in the DB are without time (just year, month, day). Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day. db.posts.find({ //query today up to tonight c...
MongoDB
11,973,304
204
Is there a way to specify a condition of "where document doesn't contain field" ? For example, I want to only find the first of these 2 because it doesn't have the "price" field. {"fruit":"apple", "color":"red"} {"fruit":"banana", "color":"yellow", "price":"2.00"}
Try the $exists operator: db.mycollection.find({ "price" : { "$exists" : false } }) and see its documentation.
MongoDB
8,567,469
204
I am trying to change the type of a field from within the mongo shell. I am doing this... db.meta.update( {'fields.properties.default': { $type : 1 }}, {'fields.properties.default': { $type : 2 }} ) But it's not working!
The only way to change the $type of the data is to perform an update on the data where the data has the correct type. In this case, it looks like you're trying to change the $type from 1 (double) to 2 (string). So simply load the document from the DB, perform the cast (new String(x)) and then save the document again. I...
MongoDB
4,973,095
204
How can I populate "components" in the example document: { "__v": 1, "_id": "5252875356f64d6d28000001", "pages": [ { "__v": 1, "_id": "5252875a56f64d6d28000002", "page": { "components": [ "525287a01877a68528000001" ] } } ], ...
Mongoose 4.5 support this Project.find(query) .populate({ path: 'pages', populate: { path: 'components', model: 'Component' } }) .exec(function(err, docs) {}); And you can join more than one deep level. Edit 03/17/2021: This is the library's implementation, what it do behind the sc...
MongoDB
19,222,520
201
I was surprised to find that the following example code only updates a single document: > db.test.save({"_id":1, "foo":"bar"}); > db.test.save({"_id":2, "foo":"bar"}); > db.test.update({"foo":"bar"}, {"$set":{"test":"success!"}}); > db.test.find({"test":"success!"}).count(); 1 I know I can loop through and keep upda...
Multi update was added recently, so is only available in the development releases (1.1.3). From the shell you do a multi update by passing true as the fourth argument to update(), where the the third argument is the upsert argument: db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true); For versions of...
MongoDB
1,740,023
200
Every day, I receive a stock of documents (an update). What I want to do is insert each item that does not already exist. I also want to keep track of the first time I inserted them, and the last time I saw them in an update. I don't want to have duplicate documents. I don't want to remove a document which has previ...
Sounds like you want to do an upsert. MongoDB has built-in support for this. Pass an extra parameter to your update() call: {upsert:true}. For example: key = {'key':'value'} data = {'key2':'value2', 'key3':'value3'}; coll.update(key, data, upsert=True); #In python upsert must be passed as a keyword argument This r...
MongoDB
2,801,008
196
So I've been learning Spring in the couples of week, been following this tutorial Building a RESTful Web Service All was well until I tried to integrate it to mongodb. So I follow this tutorial. Accessing Data with MongoDB But my practice is partially still using the first one. So my project directory structure is like...
Solved it. So by default, all packages that falls under @SpringBootApplication declaration will be scanned. Assuming my main class ExampleApplication that has @SpringBootApplication declaration is declared inside com.example.something, then all components that falls under com.example.something is scanned while com.exam...
MongoDB
42,907,553
195
I'm a little bit confused by the findAndModify method in MongoDB. What's the advantage of it over the update method? For me, it seems that it just returns the item first and then updates it. But why do I need to return the item first? I read the MongoDB: the definitive guide and it says that it is handy for manipulatin...
If you fetch an item and then update it, there may be an update by another thread between those two steps. If you update an item first and then fetch it, there may be another update in-between and you will get back a different item than what you updated. Doing it "atomically" means you are guaranteed that you are get...
MongoDB
10,778,493
195
I'm using mongoose in a script that is not meant to run continuously, and I'm facing what seems to be a very simple issue yet I can't find an answer; simply put once I make a call to any mongoose function that sends requests to mongodb my nodejs instance never stops and I have to kill it manually with, say, Ctrl+c or P...
You can close the connection with mongoose.connection.close()
MongoDB
8,813,838
195
For example, I have these documents: { "addr": "address1", "book": "book1" }, { "addr": "address2", "book": "book1" }, { "addr": "address1", "book": "book5" }, { "addr": "address3", "book": "book9" }, { "addr": "address2", "book": "book5" }, { "addr": "address2", "book": "book1" }, { "addr": "...
TLDR Summary In modern MongoDB releases you can brute force this with $slice just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number ...
MongoDB
22,932,364
194
How to I get mongo to use a mounted drive on ec2? I really do not understand. I attached a volume on ec2 formatted the drive as root and start as root and yet as root I cant access? I am running on ubuntu 12.04. No other mongo is running I see that mongo made a 'db' dir in /data i.e. /data/db cd / ls -al drwxr-xr-x...
I use this method to solve the problem: sudo chown -R mongodb:mongodb /data/db
MongoDB
15,229,412
193
I need to be able to start/stop MongoDB on the cli. It is quite simple to start: ./mongod But to stop mongo DB, I need to run open mongo shell first and then type two commands: $ ./mongo use admin db.shutdownServer() So I don't know how to stop mongo DB in one line. Any help?
Starting and Stopping MongoDB is covered in the MongoDB manual. It explains the various options of stopping MongoDB through the shell, cli, drivers etc. It also details the risks of incorrectly stopping MongoDB (such as data corruption) and talks about the different kill signals. Additionally, if you have installed Mon...
MongoDB
11,774,887
192
When i run this sql in phpmyadmin SELECT @@SQL_MODE, @@GLOBAL.SQL_MODE; it shows @@SQL_MODE STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION @@GLOBAL.SQL_MODE STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION How to Disable strict ...
Edit via SSH /etc/my.cnf file Add sql_mode=NO_ENGINE_SUBSTITUTION restart MariaDB and it will fix the issue *edit - if You have error while restarting msyql service try to add "[mysqld]" above in my.cnf
MariaDB
57,381,392
11
I'm doing unit/integration tests. SQLite doesn't support RIGHT JOIN and FULL OUTER JOIN. Is there any way to work with MySQL (or MariaDB) completely stored in memory? MySQL has MEMORY table engine, however this may generate inconsistency in my tests. I need some alternative to :memory: from SQLite but with the same fea...
MariaDB has the MEMORY storage engine: It is best-used for read-only caches of data from other tables, or for temporary work areas. That sounds exactly right for quick setup and teardown of a database during automated testing.
MariaDB
51,523,432
11
I'm using Sequelize version 4.3.0 on nodejs(v6.11.0) application having Mariadb (mysql Ver 15.1 Distrib 10.0.29-MariaDB, for debian-linux-gnu (i686) using readline 5.2 ) on Ubuntu 16.04. when application starts and calls function: Sequelize.sync(); Then sequelize connection manager throws following error: Unhandled...
I found the answer: login to mysql command line and write the following commands: use mysql; update user set authentication_string=password(''),plugin='mysql_native_password' where user='root';
MariaDB
45,051,927
11
Is there a notable difference in query performance, if the index is set on datetime type column, instead of boolean type column (and querying is done on that column)? In my current design I got 2 columns: is_active TINYINT(1), indexed deleted_at DATETIME query is SELECT * FROM table WHERE is_active = 1; Would it be a...
Here is a MariaDB (10.0.19) benchmark with 10M rows (using the sequence plugin): drop table if exists test; CREATE TABLE `test` ( `id` MEDIUMINT UNSIGNED NOT NULL, `is_active` TINYINT UNSIGNED NOT NULL, `deleted_at` TIMESTAMP NULL, PRIMARY KEY (`id`), INDEX `is_active` (`is_active`), INDEX `dele...
MariaDB
42,875,220
11
I have a query that runs in about 20 seconds on a MySQL 5.1 server but takes almost 15 minutes on a MariaDB 5.5 server. Usual suspects like key_buffer_size and tmp_table_size and max_heap_table_size are all equal (128M). Most settings are equal as far as I can see (query_cache,etc) The query: SELECT products.id, conc...
From the explanation above can be seen that the Derived Table Merge Optimization is used. That unfortunately in your case means that instead of only one full table scan over adspacesome ~6k are done. A possible solution is to disable the optimization before the query by issuing set optimizer_switch='derived_merge=off';...
MariaDB
35,011,477
11
I'm trying to setup a database schema on MariaDB which originally comes from PostgreSQL. What is the correct syntax in MariaDB for: ALTER DATABASE mydbname OWNER TO someuser and similar for granting privileges: GRANT ALL PRIVILEGES ON DATABASE mydbname TO someotheruser Both works on PostgreSQL and is valid SQL-99 syn...
Often privileges are not part of the SQL standard because every database does this there own way. MySQL and MariaDB do not have database owners like postgres. They do have a privilege systems to allow or deny accounts certain rights. The second would look like: GRANT ALL PRIVILEGES ON database.table TO 'user'@'host' [I...
MariaDB
26,561,218
11