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 want to use a graph database for a web application (involving a web of Users, Posts, Comments, Votes, Answers, Documents and Document-Merges and some other transitive relationships on Users and Documents). So I start asking myself if there is something like a design methodology for Graph Databases, i.e. a kind of ana...
The Gremlin User Group (http://tinkerpop.com/) and Neo4j User Group (https://groups.google.com/forum/?fromgroups#!forum/neo4j) are good places to discuss graph-database modeling. You can create supernodes such as "Users," but it may be better and more performant to use indexes and create an index entry for each user w...
Neo4j
10,753,331
12
I have several data sheets in the total size of 40G and would like to represent it in a graph (there could be several nodes per row, and nodes will contain most of the data in the row either in labels or properties). Could Neo4J handle this? What is the largest DB size (quantity of nodes, size on disk, etc. ) tested so...
there are several installations with over 1B-2B relationships - capacity-wise, http://docs.neo4j.org/chunked/snapshot/capabilities-capacity.html is listing the current maximum.
Neo4j
8,781,791
12
I know that there are similar questions around on Stackoverflow but I don't feel they answer the following. Graph Databases to my understanding store data following mostly this schema: Table/Collection 1: store nodes with UID Table/Collection 2: store relations referencing nodes via UID This allows storing arbitrary t...
The main difference between graph databases and triple stores is how they model the graph. In a triple store (or quad store), the data tends to be very atomic. What I mean is that the "nodes" in the graph tend to be primitive data types like string, integer, date, etc. Relationships link primitives together, and so ...
OrientDB
30,166,007
81
I am currently on design phase of a MMO browser game, game will include tilemaps for some real time locations (so tile data for each cell) and a general world map. Game engine I prefer uses MongoDB for persistent data world. I will also implement a shipping simulation (which I will explain more below) which is basicall...
Disclaimer: I am the author and owner of OrientDB. As developer, in general, I don't like companies that hide costs and let you play with their technology for a while and as soon as you're tight with it, start asking for money. Actually once you invested months to develop your application that use a non standard langua...
OrientDB
26,704,134
49
I am looking to dip my hands into the world of Multi-Model DBMS, I have no particular use cases, just want to start learning. I find that there are two prominent ones - OrientDB vs ArangoDB, but was unable to find any meaningful comparison, unopinionated between them. Can someone shed some light on the difference in fe...
Disclaimer: I would no longer recommend OrientDB, see my comments below. I can provide a slightly less biased opinion, having used both ArangoDB and OrientDB. It's still biased as I'm the author of OrientDB's node.js driver - oriento but I don't have a vested interest in either company or product, I've just necessar...
OrientDB
28,553,942
36
There is some hype around graph databases. I'm wondering why. What are the possible problems that one can be confronted with in today's web environment that can be solved using graph databases? And are graph databases suitable for classical applications, i.e. can one be used as a drop-in replacement for a Relational D...
Many relational representations of graphs aren't particularly efficient for all operations you might want to perform. For example, if one wants the connected set of all nodes where edges satisfy a given predicate, starting from a given node, there's no natural way in SQL to express that. Likely you'll either do a query...
OrientDB
1,159,190
21
Do you know any open source software that uses Orient DB? Or have you used that product yourself? Any experiences to share? I have recently looked into Orient DB, and it has nice and interesting feature set (fast, embeddable in Java, simple API) but it seems that it is not widely used. Is it just because the Orient DB...
After the total failure of ODBMS (at least from an adoption point of view), it seems obvious to me that the NoSQL movement is perceived by (ex) ODBMS players (like Versant, db4o, Orient) as an opportunity for a resurrection. This IMHO exactly the case of OrientDB which is the result of the rewrite of the Orient ODBMS e...
OrientDB
3,028,156
15
I will be constructing an ecommerce site, and would like to use a no-sql database, which will fit well with the plans for the app. But when it comes to which database would fit the job, im not sure. After comparing various DB's, the ones that seem best might be either mongo, couch, or even orientdb. I have seen argumen...
Since e-commerce can encompass everything from shopping carts through to membership and recurring subscriptions, it is hard to guess exactly what requirements and complexity you are envisioning. When constructing an e-commerce site, one of the early considerations should be investigating whether there is already an est...
OrientDB
12,488,720
14
I've been reading about OrientDB for a while now, and I'm a bit confused about the "Editions" of the software. The main version sounds like it's just the document store, but things on the internet make it sound like it's both the document and graph database. http://nosql.mypopescu.com/post/1254869909/correction-orientd...
OrientDB is a document-graph dbms because has the document-db features but handles relationships using direct links, not with JOINS like RDBMS. So you can use the standard version to map even a graph. The Graph Edition is the Standard one with bundled the TinkerPop technology stack like the Gremlin language.
OrientDB
8,479,359
14
As per OrientDB docs it says The Drop Property command removes a property from the schema. This doesn't remove the property values in records, but just change the schema information. Records will continue to have the property values if any. This is creating some issues in my code, making app throw null pointer...
Found the solution here To remove property from existing records to run following query: UPDATE <class> REMOVE <PROPERTY> WHERE <CONDITION>
OrientDB
29,545,198
13
I want to use docker-compose to compose together php and several databases (orientdb, neo4j, etc). Then get into the php container and use the shell to execute commands. Individually, all of my container work swimmingly, and when I compose them together, they all run. However, I cannot for the life of me figure out how...
So docker-compose is just a stand-in for the docker-engine client. It maintains feature parity with the client. For diagnosing problems like this, you should drop the use of docker-compose until you get it working with the regular ole client. Based on your comments here and on the other answer, it just sounds like you'...
OrientDB
37,149,001
12
Im using OrientDB type graph. I need syntax of Gremlin for search same SQL LIKE operator LIKE 'search%' or LIKE '%search%' I've check with has and filter (in http://gremlindocs.com/). However it's must determine exact value is passed with type property. I think this is incorrect with logic of search. Thanks for anythi...
For Cosmos Db Gremlin support g.V().has('foo', TextP.containing('search')) You can find the documentation Microsoft Gremlin Support docs And TinkerPop Reference
OrientDB
19,085,078
12
Are there any implementations, api or examples of OrientDB and C#. The reason I am looking at OrientDB is becuase it's the only one that I found that is a combination of Graph and Document. Any suggestions on how I should try this. My next choice is RavenDB, but I am not sure if it supports joins or linked documen...
OrientDB has an official binary driver for .NET look here http://orientdb.com/docs/3.0.x/ Example of usage OrientDB-NET.binary string release = OClient.CreateDatabasePool("127.0.0.1", 2424, "ModelTestDB", ODatabaseType.Graph, "admin", "admin", 10, "ModelTestDBAlias"); using(ODatabase database = new ODatabase("ModelTest...
OrientDB
5,421,083
10
When using MongoDB, are there any special patterns for making e.g. a paged view? say a blog that lists the 10 latest posts where you can navigate backwards to older posts. Or do one solve it with an index on e.g. blogpost.publishdate and just skip and limit the result?
Using skip+limit is not a good way to do paging when performance is an issue, or with large collections; it will get slower and slower as you increase the page number. Using skip requires the server to walk though all the documents (or index values) from 0 to the offset (skip) value. It is much better to use a range qu...
MongoDB
5,049,992
88
Using the code: all_reviews = db_handle.find().sort('reviewDate', pymongo.ASCENDING) print all_reviews.count() print all_reviews[0] print all_reviews[2000000] The count prints 2043484, and it prints all_reviews[0]. However when printing all_reviews[2000000], I get the error: pymongo.errors.OperationFailure: database...
You're running into the 32MB limit on an in-memory sort: https://docs.mongodb.com/manual/reference/limits/#Sort-Operations Add an index to the sort field. That allows MongoDB to stream documents to you in sorted order, rather than attempting to load them all into memory on the server and sort them in memory before send...
MongoDB
27,023,622
88
I am trying to fetch some ids that exist in a mongo database with the following code: client = MongoClient('xx.xx.xx.xx', xxx) db = client.test_database db = client['...'] collection = db.test_collection collection = db["..."] for cursor in collection.find({ "$and" : [{ "followers" : { "$gt" : 2000 } }, { "followers"...
You're getting this error because the cursor is timing out on the server (after 10 minutes of inactivity). From the pymongo documentation: Cursors in MongoDB can timeout on the server if they’ve been open for a long time without any operations being performed on them. This can lead to an CursorNotFound exception being...
MongoDB
24,199,729
88
How can I sort a MongoDB collection by a given field, case-insensitively? By default, I get A-Z before a-z.
Update: As of now mongodb have case insensitive indexes: Users.find({}) .collation({locale: "en" }) .sort({name: 1}) .exec() .then(...) shell: db.getCollection('users') .find({}) .collation({'locale':'en'}) .sort({'firstName':1}) Update: This answer is out of date, 3.4 will have case insensitive indexe...
MongoDB
22,931,177
88
In so many introductory examples of using MongoDB, you see code like this: var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db) { /* Some operation... CRUD, etc. */ db.close(); }); If MongoDB is like any other database system, open and cl...
Yes, that is fine and typical behavior. start your app, connect to db, do operations against the db for a long time, maybe re-connect if the connection ever dies unexpectedly, and then just never close the connection (just rely on the automatic close that happens when your process dies).
MongoDB
18,650,890
88
This is my appointment collection: { _id: ObjectId("518ee0bc9be1909012000002"), date: ISODate("2013-05-13T22:00:00Z"), patient:ObjectId("518ee0bc9be1909012000002") } { _id: ObjectId("518ee0bc9be1909012000002"), date: ISODate("2013-05-13T22:00:00Z"), patient:ObjectId("518ee0bc9be1909012000002") } { _id: ObjectId("518e...
With the latest version of mongoose (mongoose >= 3.6), you can but it requires a second query, and using populate differently. After your aggregation, do this: Patients.populate(result, {path: "patient"}, callback); See more at the Mongoose API and the Mongoose docs.
MongoDB
16,680,015
88
I have a NodeJS application with Mongoose ODM(Mongoose 3.3.1). I want to retrieve all fields except 1 from my collection.For Example: I have a collection Product Which have 6 fields,I want to select all except a field "Image" . I used "exclude" method, but got error.. This was my code. var Query = models.Product.fi...
Use query.select for field selection in the current (3.x) Mongoose builds. Prefix a field name you want to exclude with a -; so in your case: Query.select('-Image'); Quick aside: in JavaScript, variables starting with a capital letter should be reserved for constructor functions. So consider renaming Query as query i...
MongoDB
14,559,200
88
I have a document: { 'profile_set' : [ { 'name' : 'nick', 'options' : 0 }, { 'name' : 'joe', 'options' : 2 }, { 'name' : 'burt', 'options' : 1 } ] } and would like to add a new document to the profile_set set if the name doesn't already exist (regardless of the option). So in this example if I tried ...
You can qualify your update with a query object that prevents the update if the name is already present in profile_set. In the shell: db.coll.update( {_id: id, 'profile_set.name': {$ne: 'nick'}}, {$push: {profile_set: {'name': 'nick', 'options': 2}}}) So this will only perform the $push for a doc with a matc...
MongoDB
14,527,980
88
I have two keys A and B and their existence in the document is mutually exclusive. I have to group by A when A exists and group by B when B exists. So I am $projecting the required value into a computed key called MyKey on which I'll perform a $group. But it looks like I'm making a mistake with the syntax. I tried writ...
Use $ifNull instead of $cond in your $project: { $project: {MyKey: {$ifNull: ['$A', '$B'] }}} If A exists and is not null its value will be used; otherwise the value of B is used.
MongoDB
14,213,636
88
Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some documents, and make modification, then save them right back. This is an example: db.open(function (err, db) { db.collection('foo', function (err, collection) { var cursor = collection.find({}); cursor.each(function (err,...
Here's a potential solution based on the counting approach (I haven't tested it and there's no error trapping, but it should convey the idea). The basic strategy is: Acquire the count of how many records need to be updated, save each record asynchronously and a callback on success, which will decrement the count and cl...
MongoDB
8,373,905
88
I've been trying to discover how to use MongoDB with Node.js and in the docs it seems the suggested way is to use callbacks. Now, I know that it is just a matter of preference, but I really prefer using promises. The problem is that I didn't find how to use them with MongoDB. Indeed, I've tried the following: var Mongo...
Your approach is almost correct, just a tiny mistake in your argument var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost:27017/example' MongoClient.connect(url) .then(function (db) { // <- db as first argument console.log(db) }) .catch(function (err) {})
MongoDB
37,911,838
87
while trying this mongo command in ubuntu I am getting this error. ritzysystem@ritzysystem-Satellite-L55-A:~$ mongo MongoDB shell version: 2.6.1 connecting to: test 2014-10-06T12:59:35.802+0530 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused 2014-10-06T12:59:35.80...
Run the following command : sudo rm /var/lib/mongodb/mongod.lock sudo service mongod restart Connection refused to MongoDB errno 111 MacOS: rm /usr/local/var/mongodb/mongod.lock sudo service mongod restart
MongoDB
26,211,671
87
I need to import (restore) a collection generated with mongodump into an existing database and I'd like the records to be merged into the existing collection. Does mongorestore merge the records in the same collection or it will drop the existing collection before restoring the records?
mongorestore will only drop the existing collection if you use the --drop argument. If you don't use --drop, all documents will be inserted into the existing collection, unless a document with the same _id already exists. Documents with the same _id will be skipped, they are not merged. So mongorestore will never delet...
MongoDB
4,021,762
87
I develop a new website and I want to use GridFS as storage for all user uploads, because it offers a lot of advantages compared to a normal filesystem storage. Benchmarks with GridFS served by nginx indicate, that it's not as fast as a normal filesystem served by nginx. Benchmark with nginx Is anyone out there, who u...
I use gridfs at work on one of our servers which is part of a price-comparing website with honorable traffic stats (arround 25k visitors per day). The server hasn't much ram, 2gigs, and even the cpu isn't really fast (Core 2 duo 1.8Ghz) but the server has plenty storage space : 10Tb (sata) in raid 0 configuration. The ...
MongoDB
3,413,115
87
Due to simple setup and low costs I am considering using AWS S3 bucket instead of a NoSQL database to save simple user settings as a JSON (around 30 documents). I researched the following disadvantages of not using a database which are not relevant for my use case: Listing of buckets/files will cost you money. No upda...
You are "considering using AWS S3 bucket instead of a NoSQL database", but the fact is that Amazon S3 effectively is a NoSQL database. It is a very large Key-Value store. The Key is the filename, the Value is the contents of the file. If your needs are simply "Store a value with this key" and "Retrieve a value with thi...
MongoDB
56,108,144
86
I am someone new to mongoDB and has absolutely no knowledge regarding databases so would like to know what is a cluster in MongoDB and what is the point of connecting to one in MongoDB? Is it a must to connect to one or can we just connect to the localhost?
A mongodb cluster is the word usually used for sharded cluster in mongodb. The main purposes of a sharded mongodb are: Scale reads and writes along several nodes Each node does not handle the whole data so you can separate data along all the nodes of the shard. Each node is a member of a shard (which is a replicaset, ...
MongoDB
43,445,975
86
I want to use Dockerizing MongoDB and store data in local volume. But .. failed ... It has mongo:latest images kerydeMacBook-Pro:~ hu$ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE mongo latest b11eedbc330f 2 weeks ago ...
Try and check docker logs to see what was going on when the container stopped and go in "Existed" mode. See also if specifying the full path for the volume would help: docker run -p 27017:27017 -v /home/<user>/data:/data/db ... The OP adds: docker logs mongo exception in initAndListen: 98 Unable to create/open loc...
MongoDB
35,400,740
86
We've recently hit the >2 Million records for one of our main collections and now we started to suffer for major performance issues on that collection. They documents in the collection have about 8 fields which you can filter by using UI and the results are supposed to sorted by a timestamp field the record was process...
This is searching the needle in a haystack. We'd need some output of explain() for those queries that don't perform well. Unfortunately, even that would fix the problem only for that particular query, so here's a strategy on how to approach this: Ensure it's not because of insufficient RAM and excessive paging Enable ...
MongoDB
19,559,405
86
What is the difference between _id and id in mongoose? Which is better for referencing?
From the documentation: Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString. So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB docume...
MongoDB
15,724,272
86
Just a simple query, for example with a double ref in the model. Schema / Model var OrderSchema = new Schema({ user: { type : Schema.Types.ObjectId, ref : 'User', required: true }, meal: { type : Schema.Types.ObjectId, ref : 'Meal', required: t...
You're already using the correct syntax of: OrderModel.find() .populate('user') .populate('meal') .exec(function (err, results) { // callback }); Perhaps the meal ObjectId from the order isn't in the Meals collection?
MongoDB
12,821,596
86
I've installed the mongodb 2.0.3, using the mongodb-10gen debian package. Everything went well, except the service which is installed by default is not starting up when computer starts. The mongod is running only as root user. maybe this is the reason. but as far as I know, the services should be running since they are...
On my ubuntu server, just run: sudo rm /var/lib/mongodb/mongod.lock mongod --repair sudo service mongodb start
MongoDB
9,884,233
86
When using MongoDB's .stats() function to determine document size, are the values returned in bits or bytes?
Running the collStats command - db.collection.stats() - returns all sizes in bytes, e.g. > db.foo.stats() { "size" : 715578011834, // total size (bytes) "avgObjSize" : 2862, // average size (bytes) } However, if you want the results in another unit then you can also pass in a scale argument. For example, t...
MongoDB
6,082,748
86
My code was working before initially but I don't know why it just stopped working and gave me this error: MongooseError: Operation `users.findOne()` buffering timed out after 10000ms at Timeout.<anonymous> (/Users/nishant/Desktop/Yourfolio/backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:...
In my experience this happens when your database is not connected, Try checking out following things - Is you database connected and you are pointing to the same url from your code. check if your mongoose.connect(...) code is loading. I faced this issue where I was running the node index.js from my terminal and mongo...
MongoDB
65,408,618
85
I updated to MacOS 10.15 (Catalina) today. When I run mongod in the terminal it cannot find the /data/db directory: ➜ /Users/william > mongod 2019-10-08T17:02:44.183+0800 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none' 2019-10-08T17:02:44.209+0800 I CONT...
This is the main error: exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating Catalina has a surprise change: it won't allow changes to the root directory (this was discussed in a forum thread as well): % sudo mkdir -p /data/db mkdir: /data/db: Read-only file system Unfortunate...
MongoDB
58,283,257
85
I have a Linode server running Ubuntu 12.04 LTS and MongoDB instance (service is running and CAN connect locally) that I can't connect to from an outside source. I have added these two rules to my IP tables, where < ip address > is the server I want to connect FROM (as outlined in this MongoDB reference): iptables -A I...
Thanks for the help everyone! Turns out that it was an iptable conflict. Two rules listing the port open (which resulted in a closed port). However, one of the comments by aka and another by manu2013 were problems that I would have run into, if not for the conflict. So! Always remember to edit the /etc/mongod.conf fil...
MongoDB
24,899,849
85
I'm using Node.js program to insert data into a MongoDB database. I have inserted data into a collection named "repl-failOver". var mongoClient = require("mongodb").MongoClient; mongoClient.connect("mongodb://localhost:30002/test", function(err, db) { if (err) throw err; db.collection("repl-failOver").insert( {...
Use this syntax: db['repl-failOver'].find({}) or db.getCollection('repl-failOver').find({}) You can find more information in the Executing Queries section of the manual: If the mongo shell does not accept the name of the collection, for instance if the name contains a space, hyphen, or starts with a number, you ...
MongoDB
24,711,939
85
I have gone through several articles and examples, and have yet to find an efficient way to do this SQL query in MongoDB (where there are millions of rows documents) First attempt (e.g. from this almost duplicate question - Mongo equivalent of SQL's SELECT DISTINCT?) db.myCollection.distinct("myIndexedNonUniqueField")...
1) The easiest way to do this is via the aggregation framework. This takes two "$group" commands: the first one groups by distinct values, the second one counts all of the distinct values pipeline = [ { $group: { _id: "$myIndexedNonUniqueField"} }, { $group: { _id: 1, count: { $sum: 1 } } } ]; // // Run the...
MongoDB
11,782,566
85
Is there any difference between using the field ID or _ID from a MongoDB document? I am asking this, because I usually use "_id", however I saw this sort({id:-1}) in the documentation: http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Sortbyidtosortbyinsertiontime EDIT Turns out the docs wer...
I expect it's just a typo in the documentation. The _id field is primary key for every document. It's called _id and is also accessible via id. Attempting to use an id key may result in a illegal ObjectId format error. That section is just indicating that the automatically generated ObjectIDs start with a timestamp so ...
MongoDB
9,694,460
85
I've installed MongoDB v4.0 for the most amazing feature of it Transaction in Nodejs with mongodb 3.1 as a driver. When I try to use a transaction session I've faced this error: MongoError: Transaction numbers are only allowed on a replica set member or mongos. What's that and how can I get rid of it?
Transactions are undoubtedly the most exciting new feature in MongoDB 4.0. But unfortunately, most tools for installing and running MongoDB start a standalone server as opposed to a replica set. If you try to start a session on a standalone server, you'll get this error. In order to use transactions, you need a MongoDB...
MongoDB
51,461,952
84
I have collection foo with documents like: {site_id: 'xxx', title: {ru: 'a', en: 'b'}, content: {ru: 'a', en: 'b'}} {site_id: 'xxx', title: {ru: 'c', de: 'd'}, content: {ru: 'c', de: 'd'}} I need to update multiple fields which are can exists or not: db.foo.update( { site_id: 'xxx'}, { $set: {'title.de': ''...
You can add a query to your update statement: db.foo.update({'title.de': {$exists : false}}, {$set: {'title.de': ''}}) Update For your modified question my solution looks like this - would that work for you? (If not, why?) db.foo.update({site_id: 'xxx', 'title.de': {$exists : false}}, {$set: {'title.de': ''}, {multi: ...
MongoDB
24,824,657
84
I want to get updated documents. This is my original code and it successfully updates but doesn't return the document. collection.update({ "code": req.body.code },{$set: req.body.updatedFields}, function(err, results) { res.send({error: err, affected: results}); db.close...
collection.update() will only report the number of documents that were affected to its own callback. To retrieve the documents while modifying, you can use collection.findOneAndUpdate() instead (formerly .findAndModify()). collection.findOneAndUpdate( { "code": req.body.code }, { $set: req.body.updatedFields },...
MongoDB
24,747,189
84
I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. This forces me to issue a redundant query without the limit() function in order for me to also capture the total number of ...
Mongodb 3.4 has introduced $facet aggregation which processes multiple aggregation pipelines within a single stage on the same set of input documents. Using $facet and $group you can find documents with $limit and can get total count. You can use below aggregation in mongodb 3.4 db.collection.aggregate([ { "$fac...
MongoDB
21,803,290
84
I've got a simple app set up that shows a list of Projects. I've removed the autopublish package so that I'm not sending everything to the client. <template name="projectsIndex"> {{#each projects}} {{name}} {{/each}} </template> When autopublish was turned on, this would display all the projects...
Collections, publications and subscriptions are a tricky area of Meteor, that the documentation could discuss in more detail, so as to avoid frequent confusion, which sometimes get amplified by confusing terminology. Here's Sacha Greif (co-author of DiscoverMeteor) explaining publications and subscriptions in one slide...
MongoDB
19,826,804
84
I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation: We may also define our own custom document instance methods too. // define a schema var animalSchema = new Schema({ name: String, type: String }); // assign a function to the "methods" object of our an...
statics are the methods defined on the Model. methods are defined on the document (instance). You might use a static method like Animal.findByName: const fido = await Animal.findByName('fido'); // fido => { name: 'fido', type: 'dog' } And you might use an instance method like fido.findSimilarTypes: const dogs = await ...
MongoDB
29,664,499
83
I have the following problem retrieving data from MongoDB using mongoose. Here is my Schema: const BookSchema = new Schema( { _id:Number, title:String, authors:[String], subjects:[String] } ); as you can see i have 2 arrays embedded in the object, let's say the content of the...
You almost answered this yourself in your tags. MongoDB has a $regex operator which allows a regular expression to be submitted as a query. So you query for strings containing "Alex" you do this: Books.find( { "authors": { "$regex": "Alex", "$options": "i" } }, function(err,docs) { } ); You can also do t...
MongoDB
26,814,456
83
I have two collections. The first collection contains students: { "_id" : ObjectId("51780f796ec4051a536015cf"), "name" : "John" } { "_id" : ObjectId("51780f796ec4051a536015d0"), "name" : "Sam" } { "_id" : ObjectId("51780f796ec4051a536015d1"), "name" : "Chris" } { "_id" : ObjectId("51780f796ec4051a536015d2"), "name" : ...
[edit based on this now being possible in recent versions] [Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled. db.student.find({}, {_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}}) and you will get back w...
MongoDB
16,198,429
83
While using Mongodb console or shell sometimes my screen is cluttered with a lot of previous output which I do not need. So, is there a function to clear console in MongoDB? Something like an analog of clear in MatLab. I have tried clc, clear but with no success.
Judging by Jira they have done it: You need to write cls in the shell. You can also use a hotkey: CTRL + L. In macOS: Command + K. Check more hotkeys for the shell here.
MongoDB
13,327,218
83
I have tried MongoMapper and it is feature complete (offering almost all AR functionality) but i was not very happy with the performance when using large datasets. Has anyone compared with Mongoid? Any performance gains ?
I have used MongoMapper for awhile but decided to migrate to MongoId. The reason is hidden issues plus arrogance towards users. I had to jump through hoops to make MongoMapper work with Cucumber (succeeded in the end) and to put a couple of patches even the project was simple, but it's not the point. When I tried to su...
MongoDB
1,958,365
83
When I try to run Mongod in terminal I got this message : 2015-05-14T17:33:04.554+0700 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating 2015-05-14T17:33:04.554+0700 I CONTROL [initandlisten] dbexit: rc: 100 and running mongo command : MongoDB shell version:...
MongoDB needs data directory to store data. Default path is /data/db When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user. If you want to change the path of your data directory then you should specify it while star...
MongoDB
30,235,200
82
Is there an easy way to "$push" all fields of a document? For example: Say I have a Mongo collection of books: {author: "tolstoy", title:"war & peace", price:100, pages:800} {author: "tolstoy", title:"Ivan Ilyich", price:50, pages:100} I'd like to group them by author - for each author, list his entire book objects: ...
You can use $$ROOT { $group : { _id : "$author", books: { $push : "$$ROOT" } }} Found here: how to use mongodb aggregate and retrieve entire documents
MongoDB
22,150,205
82
In my collections, documents contains key like status and timestamp. When I want to find latest ten documents then I write following query db.collectionsname.find().sort({"timestamp"-1}).limit(10) This query gives me results which I want but when I want to delete latest ten documents then I was writing the following q...
You can't set a limit when using remove or findAndModify. So, if you want to precisely limit the number of documents removed, you'll need to do it in two steps. db.collectionName.find({}, {_id : 1}) .limit(100) .sort({timestamp:-1}) .toArray() .map(function(doc) { return doc._id; }); // Pull out just ...
MongoDB
19,065,615
82
Is there a simple way to reset the data from a meteor deployed app? So, for example, if I had deployed an app named test.meteor.com — how could I easily reset the data that has been collected by that app? Locally I run meteor reset, but I am unsure of what to do in production.
If you have your app with you you could do this in your project directory meteor deploy test.meteor.com --delete meteor deploy test.meteor.com The first deletes the app so its all blank. The second deploys a fresh instance of it back.
MongoDB
15,583,107
82
So, I'm sure I'm missing something simple here, but when I run mongo as a daemon (using mongod --fork or just mongod), I see different database content than if I just run "mongo" on the host machine. My only assumption is that the data is being stored somewhere other than /data/db when it's running just the shell, and ...
I think there is some confusion here. mongod is the "Mongo Daemon" it's basically the host process for the database. When you start mongod you're basically saying "start the MongoDB process and run it in the background". mongod has several default parameters, such as storing data in /data/db and running on port 27017. ...
MongoDB
4,883,045
82
i've seen many answers to this question here, but i still don't get it (maybe because they use more "complex" examples)... So what im trying to do is a schema for a "Customer", and it will have two fields that will have nested "subfields", and others that may repeat. here is what i mean: let customerModel = new Schema(...
const mongoose = require("mongoose"); // Make connection // https://mongoosejs.com/docs/connections.html#error-handling mongoose.connect("mongodb://localhost:27017/test", { useNewUrlParser: true, useUnifiedTopology: true, }); // Define schema // https://mongoosejs.com/docs/models.html#compiling const AddressSchem...
MongoDB
39,596,625
81
I need to retrieve the entire single object hierarchy from the database as a JSON. Actually, the proposal about any other solution to achieve this result would be highly appreciated. I decided to use MongoDB with its $lookup support. So I have three collections: party { "_id" : "2", "name" : "party2" } { "_id" : "5", "...
The cause of your 'troubles' is the second aggregation stage - { $unwind: "$address" }. It removes record for party with _id: 4 (because its address array is empty, as you mention) and produces two records for parties _id: 1 and _id: 5 (because each of them has two addresses). To prevent removing of parties without a...
MongoDB
36,019,713
81
When using a FindOne() using MongoDB and C#, is there a way to ignore fields not found in the object? EG, example model. public class UserModel { public ObjectId id { get; set; } public string Email { get; set; } } Now we also store a password in the MongoDB collection, but do not want to bind it to out objec...
Yes. Just decorate your UserModel class with the BsonIgnoreExtraElements attribute: [BsonIgnoreExtraElements] public class UserModel { public ObjectId id { get; set; } public string Email { get; set; } } As the name suggests, the driver would ignore any extra fields instead of throwing an exception. More infor...
MongoDB
23,448,634
81
I have a Mongo database that I did not create or architect, is there a good way to introspect the db or print out what the structure is to start to get a handle on what types of data are being stored, how the data types are nested, etc?
Just query the database by running the following commands in the mongo shell: use mydb //this switches to the database you want to query show collections //this command will list all collections in the database db.collectionName.find().pretty() //this will show all documents in the database in a readable format; do the...
MongoDB
14,713,179
81
How can I find all the objects in a database with where a field of a object contains a substring? If the field is A in an object of a collection with a string value: I want to find all the objects in the db "database" where A contains a substring say "abc def". I tried: db.database.find({A: {$regex: '/^*(abc def)*$/''...
Instead of this: db.database.find({A: {$regex: '/^*(abc def)*$/''}}) You should do this: db.database.find({A: /abc def/i }) ^* is not actually valid syntax as ^ and $ are anchors and not something that is repeatable. You probably meant ^.* here. But there is no need for ^.* as that simply means "Everything up to the ...
MongoDB
10,242,501
81
Campaign.find {client_id:req.param('client_id')}, (error, campaigns) -> if error response = error: error.message else for campaign in campaigns query = campaign_id: campaign._id console.log query CampaignResponse.find query, (err, campaignResponsesCount) -...
A couple tips: Try running the same query from mongodb at the command line, see if you get any results. Is the "campaign_id" defined as an ObjectId in your schema? If so, try searching using the ObjectId type. For example: var ObjectId = require('mongoose').Types.ObjectId; var query = { campaign_id: new ObjectId(ca...
MongoDB
7,878,557
81
I have a large CSV file containing a list of stores, in which one of the field is ZipCode. I have a separate MongoDB database called ZipCodes, which stores the latitude and longitude for any given zip code. In SQL Server, I would execute a stored procedure called InsertStore which would do a look up on the ZipCodes tab...
The closest thing to an equivalent of a stored procedure in mongodb is stored javascript. A good introduction to stored javascript is available in this article on Mike Dirolf's blog.
MongoDB
3,876,049
81
I've googled around but couldn't find a working MongoDB viewer or data browser. An ideal (for my needs) tool would be a web based viewer with dead simple features (browsing and doing queries).
You have : Mongo3 futon4mongo
MongoDB
2,411,087
81
I'm trying to determine the best way to deal with a composite primary key in a mongo db. The main key for interacting with the data in this system is made up of 2 uuids. The combination of uuids is guaranteed to be unique, but neither of the individual uuids is. I see a couple of ways of managing this: Use an object f...
You should go with option 1. The main reason is that you say you are worried about performance - using the _id index which is always there and already unique will allow you to save having to maintain a second unique index. For option 1, I'm worried about the insert performance do to having non sequential keys. I kno...
MongoDB
23,164,417
80
I've a mongodb collection in this form: {id=ObjectId(....),key={dictionary of values}} where dictionary of values is {'a':'1','b':'2'.....} Let dictionary of values be 'd'. I need to update the values of the key in the 'd'. i.e I want to change 'a':'1' to 'a':'2' How can do I this in pymongo? Code goes something like ...
You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child va...
MongoDB
13,710,770
80
I'm asking this because when I write unit tests, I want to drop the test database and insert some initialize data, and also check the data in mongodb in testing. So I need raw operations to mongodb. How to do this in mongoose? What I can do now is just create the connection, and not find any document in mongoose's offi...
You can run mongodb commands using the native NodeJS driver by using mongoose.connection.db. This accesses the NodeJS MongoDB driver, and you don't need to create a mongoose model. An insert mongoose.connection.db.collection('userCollection').insert({ username: 'captain1', firstName: 'Steve', lastName: 'Rogers',...
MongoDB
10,519,432
80
How do I get the timestamp from the MongoDB id?
The timestamp is contained in the first 4 bytes of a mongoDB id (see: http://www.mongodb.org/display/DOCS/Object+IDs). So your timestamp is: timestamp = _id.toString().substring(0,8) and date = new Date( parseInt( timestamp, 16 ) * 1000 )
MongoDB
6,452,021
80
I have my json_file.json like this: [ { "project": "project_1", "coord1": 2, "coord2": 10, "status": "yes", "priority": 7 }, { "project": "project_2", "coord1": 2, "coord2": 10, "status": "yes", "priority": 7 }, { "project": "project_3", "coord1": 2, "coord2": 10, ...
The mongoimport tool has an option: --jsonArray treat input source as a JSON array Or it is possible to import from file containing same data format as the result of db.collection.find() command. Here is example from university.mongodb.com courseware some content from grades.json: { "_id" : { "$o...
MongoDB
30,380,751
79
I know that MongoDB supports the syntax find{array.0.field:"value"}, but I specifically want to do this for the last element in the array, which means I don't know the index. Is there some kind of operator for this, or am I out of luck? EDIT: To clarify, I want find() to only return documents where a field in the las...
In 3.2 this is possible. First project so that myField contains only the last element, and then match on myField. db.collection.aggregate([ { $project: { id: 1, myField: { $slice: [ "$myField", -1 ] } } }, { $match: { myField: "myValue" } } ]);
MongoDB
28,680,295
79
Trying to create a MongoDB data source with icCube. The idea is to return the size of an array as a new field. Something like : $project: { "people": 1, "Count myFieldArray" : {$size : "$myFieldArray" } } But I'm getting for some records the following error : The argument to $size must be an Array, but was of type...
You can use the $ifNull operator here. It seems the field is either not an array or not present by the given error: { "$project": { "people": 1, "Count": { "$size": { "$ifNull": [ "$myFieldArray", [] ] } } }} Also you might want to check for the $type in your $match in case these do exist but are ...
MongoDB
24,201,120
79
I'm aware of the $addToSet method for MongoDB, but I can't find a "remove" equivalent anywhere in the docs. What's the best way to achieve this? Trying to achieve something like the following: obj = { name: 'object1', tags: ['fus', 'ro', 'dah'] } db.collection.update({ name: 'object1' }, { $removeFromSet: { ...
I think you are looking for $pull, which "removes all instances of a value from an existing array". db.collection.update( {name: 'object1'}, {$pull: { tags: 'dah'}});
MongoDB
18,395,412
79
I'm new to MongoDB. I currently have a dump of a mongo db (i.e. directory of .bson files) and am trying to import that into mongo. I installed mongo as per the instructions on http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/. I'm currently trying to test starting a local mongo instance by running mongod...
There is nothing wrong, you have started the server, it is running and listening on port 27017. Now you can start to interact with the server, for example just open a new terminal tab and run mongo ,which will open mongo's interactive console and connects to the default server(localhost:27017) If you want to run mongod...
MongoDB
12,514,119
79
The list of MongoDB GUI client apps on the official site is outdated: some clients are not supported, some are heavily bound to .NET and not runnable on Linux. And all of them lack the ability to edit stored documents (i.e. provide read-only access). I need a GUI client that: Works on Linux (but not web); Is free; Sup...
Robomongo - cross-platform MongoDB GUI client. Update: Mac OS X and Linux(as Debian/Ubuntu, RHEL/CentOS packages) versions released. Update: Robomongo officially changed it's name and released two different products Studio 3T and Robo 3T. Old robomongo is now called Robo 3T. Studio is for professionals. Update: from Oc...
MongoDB
10,227,664
79
Anyone has experiences with MongoKit, MongoEngine or Flask-MongoAlchemy for Flask? Which one do you prefer? Positive or negative experiences?. Too many options for a Flask-Newbie.
I have invested a lot of time evaluating the popular Python ORMs for MongoDB. This was an exhaustive exercise, as I really wanted to pick one. My conclusion is that an ORM removes the fun out of MongoDB. None feels natural, they impose restrictions similar to the ones which made me move away from relational databases i...
MongoDB
9,447,629
79
What's the best practice (or tool) for updating/migrating Mongoose schemas as the application evolves?
It's funny though, MongoDB was born to respond to the schema problems in RDBMS. You don't have to migrate anything, all you have to do is set the default value in the schema definition if the field is required. new Schema({ name: { type: string } }) to: new Schema({ name: { type: string }, birthplace: { ty...
MongoDB
7,617,002
79
I'm running an update on my MongoDB from Python. I have this line: self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True}) But it throws this error: raise TypeError("upsert must be an instance of bool") But True looks like an instance of bool to me! How should I correctly write this update...
The third argument to PyMongo's update() is upsert and must be passed a boolean, not a dictionary. Change your code to: self.word_counts[source].update({'date':posttime}, {"$inc" : words}, True) Or pass upsert=True as a keyword argument: self.word_counts[source].update({'date':posttime}, {"$inc" : words}, upsert=True)...
MongoDB
5,055,797
79
What are different ways to insert a document(record) into MongoDB using Mongoose? My current attempt: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var notificationsSchema = mongoose.Schema({ "datetime" : { type: Date, default: Date.now }, "ownerId":{ type:String...
The .save() is an instance method of the model, while the .create() is called directly from the Model as a method call, being static in nature, and takes the object as a first parameter. var mongoose = require('mongoose'); var notificationSchema = mongoose.Schema({ "datetime" : { type: Date, defaul...
MongoDB
38,290,684
78
Let us have a MongoDB collection which has three docs.. db.collection.find() { _id:'...', user: 'A', title: 'Physics', Bank: 'Bank_A' } { _id:'...', user: 'A', title: 'Chemistry', Bank: 'Bank_B' } { _id:'...', user: 'B', title: 'Chemistry', Bank: 'Bank_A' } We have a doc, doc = { user: 'B', title: 'Chemistry', B...
Don't use insert. Use update with upsert=true. Update will look for the document that matches your query, then it will modify the fields you want and then, you can tell it upsert:True if you want to insert if no document matches your query. db.collection.update( <query>, <update>, { upsert: <boolean>, ...
MongoDB
24,122,981
78
To modify a field in an existing entry in mongoose, what is the difference between using model = new Model([...]) model.field = 'new value'; model.save(); and this Model.update({[...]}, {$set: {field: 'new value'}); The reason I'm asking this question is because of someone's suggestion to an issue I posted yesterday:...
Two concepts first. Your application is the Client, Mongodb is the Server. The main difference is that with .save() you already have an object in your client side code or had to retrieve the data from the server before you are writing it back, and you are writing back the whole thing. On the other hand .update() does n...
MongoDB
22,278,761
78
How do I show the current user that I'm logged into the mongo shell as? This is useful to know because it is possible to change the user that you are logged in as—e.g. db.auth("newuser", "password")—while in the interactive shell. One can easily lose track. Update Using the accepted answer as a base, I changed the prom...
The connectionStatus command shows authenticated users (if any, among some other data): db.runCommand({connectionStatus : 1}) Which results in something like bellow: { "authInfo" : { "authenticatedUsers" : [ { "user" : "aa", "u...
MongoDB
21,414,608
78
For example I have the following data in MongoDB: { "_id" : ObjectId("524091f99c49c4c3f66b0e46"), "hour" : 10, "incoming", 100} { "_id" : ObjectId("5240a045dbeff33c7333aa51"), "hour" : 11, "incoming", 200} { "_id" : ObjectId("5240a2ecda0d37f35c618aca"), "hour" : 12, "incoming", 300} Now I want to query "SUM the number...
As llovet suggested, the aggregation framework is the way to go. Here's what your query would look like: db.CollectionNameGoesHere.aggregate({ $match: { $and: [ { hour: { $gte: 11 } }, { hour: { $lte: 12 } } ] } }, { $group: { _id : null, sum : { $sum: "$incoming" } } }); You can also shape the...
MongoDB
18,969,916
78
My Ubuntu computer had crashed, and when I restarted it MongoDB wasn't working. I tried the following commands, and got the following output: $ mongo Error: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js:91 exception: connect failed $ service mongodb status mongodb stop/waiting $ service mongodb ...
The log file is telling you that you have an "old lock file". MongoDB keeps a lock file while it's running. It creates this file when it is started, and deletes it when it's stopped. When the computer crashes (or MongoDB crashes, e.g. via kill), this file is not deleted, and thus the database does not start. The existe...
MongoDB
13,700,261
78
My database of choice is MongoDB. I'm writing a data-layer API to abstract implementation details from client applications - that is, I'm essentially providing a single public interface (an object which acts as an IDL). I'm testing my logic as I go in a TDD manner. Before each unit test, an @Before method is called to ...
Technically tests that talk to a database (nosql or otherwise) are not unit tests, as the tests are testing interactions with an external system, and not just testing an isolated unit of code. However tests that talk to a database are often extremely useful, and are often fast enough to run with the other unit tests. ...
MongoDB
7,413,985
78
how can i set a callback for the error handling if mongoose isn't able to connect to my DB? i know of connection.on('open', function () { ... }); but is there something like connection.on('error', function (err) { ... }); ?
When you connect you can pick up the error in the callback: mongoose.connect('mongodb://localhost/dbname', function(err) { if (err) throw err; });
MongoDB
6,676,499
78
How do I connect to mongodb with node.js? I have the node-mongodb-native driver. There's apparently 0 documentation. Is it something like this? var mongo = require('mongodb/lib/mongodb'); var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {}); Where do I put the username and the password? Al...
Per the source: After connecting: Db.authenticate(user, password, function(err, res) { // callback });
MongoDB
4,688,693
78
I have a list of documents, each with lat and lon properties (among others). { 'lat': 1, 'lon': 2, someotherdata [...] } { 'lat': 4, 'lon': 1, someotherdata [...] } [...] I want to modify it so that it looks like this: { 'coords': {'lat': 1, 'lon': 2}, someotherdata [...]} { 'coords': {'lat': 4, 'lon': 1}, someother...
Update: If all you have to do is change the structure of a document without changing the values, see gipset's answer for a nice solution. According to a (now unavailable) comment on the Update documentation page, you cannot reference the current document's properties from within an update(). You'll have to iterate thr...
MongoDB
3,788,256
78
I'm using: Python 3.4.2 PyMongo 3.0.2 mongolab running mongod 2.6.9 uWSGI 2.0.10 CherryPy 3.7.0 nginx 1.6.2 uWSGI start params: --socket 127.0.0.1:8081 --daemonize --enable-threads --threads 2 --processes 2 I setup my MongoClient ONE time: self.mongo_client = MongoClient('mongodb://user:pw@host.mongolab.com:port/myd...
We're investigating this problem, tracked in PYTHON-961. You may be able to work around the issue by passing connect=False when creating instances of MongoClient. That defers background connection until the first database operation is attempted, avoiding what I suspect is a race condition between spin up of MongoClient...
MongoDB
31,030,307
77
I'm on osx6.8 and need to install an earlier version of Mongodb, how do I install an earlier version with HomeBrew? The below didn't work :( dream-2:app2 star$ brew install mongodb-2.6.10 Error: No available formula for mongodb-2.6.10 Searching formulae... Searching taps... dream-2:app2 star$ Edit: I'm getting a mes...
Note: In September 2019 mongodb was removed from homebrew core, so these instructions have been updated to use mongodb-community instead, installed from the external tap. If your current installation is still the pre-September mongodb package then you will need to replace mongodb-community with just mongodb on the lin...
MongoDB
30,379,127
77
I am writing a NodeJS server with ExpressJS, PassportJS, MongoDB and MongooseJS. I just managed to get PassportJS to use user data obtained via Mongoose to authenticate. But to make it work, I had to use a "findById" function like below. var UserModel = db.model('User',UserSchema); UserModel.findById(id, function (err...
findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here. Example: // Search by ObjectId var id = "56e6dd2eb4494ed008d595bd"; UserModel.findById(id, function (err, user) { ... } ); Functionally, it's the same as calling: UserMod...
MongoDB
12,483,632
77
MongoDB is fast, but only when your working set or index can fit into RAM. So if my server has 16G of RAM, does that mean the sizes of all my collections need to be less than or equal to 16G? How does one say "ok this is my working set, the rest can be "archived?"
"Working set" is basically the amount of data AND indexes that will be active/in use by your system. So for example, suppose you have 1 year's worth of data. For simplicity, each month relates to 1GB of data giving 12GB in total, and to cover each month's worth of data you have 1GB worth of indexes again totalling 12GB...
MongoDB
6,453,584
77
Could anybody tell me what is the pros and cons of mongodb, especially comparing with the relational database? including ACID, scalability, throughput, main memory usage, insert/query performance and index size etc.
Some general points on MongoDB Pros: schema-less. If you have a flexible schema, this is ideal for a document store like MongoDB. This is difficult to implement in a performant manner in RDBMS ease of scale-out. Scale reads by using replica sets. Scale writes by using sharding (auto balancing). Just fire up another m...
MongoDB
5,244,437
77
The records in my database are {"_id":"1","fn":"sagar","ln":"Varpe"} {"_id":"1","fn":"sag","score":"10"} {"_id":"1","ln":"ln1","score":"10"} {"_id":"1","ln":"ln2"} I need to design a MongoDB query to find all records that have a given key. For example, if I pass ln as a parameter to the query it shuold return all ...
To find if a key/field exists in your document use the $exists operator. Via the MongoDB shell ... db.things.find( { ln : { $exists : true } } );
MongoDB
4,582,354
77
I know that MongoDB accepts and retrieves records as JSON/BSON objects, but how does it actually store these files on disk? Are they stored as a collection of individual *.json files or as one large file? I have a hunch as to the latter, since the MongoDB docs state that it works best on systems with ext4/xfs, which ar...
A given mongo database is broken up into a series of BSON files on disk, with increasing size up to 2GB. BSON is its own format, built specifically for MongoDB. These slides should answer all of your questions: http://www.slideshare.net/mdirolf/inside-mongodb-the-internals-of-an-opensource-database
MongoDB
4,127,386
77
What's the difference between insert(), insertOne(), and insertMany() methods on MongoDB. In what situation should I use each one? I read the docs, but it's not clear when use each one.
What's the difference between insert(), insertOne() and insertMany() methods on MongoDB db.collection.insert() as mentioned in the documentation inserts a document or documents into a collection and returns a WriteResult object for single inserts and a BulkWriteResult object for bulk inserts. > var d = db.collection...
MongoDB
36,792,649
76
I am using nodejs with the node-mongodb-native driver (http://mongodb.github.io/node-mongodb-native/). I have documents with a date property stored as ISODate type. Through nodejs, I am using this query: db.collection("log").find({ localHitDate: { '$gte': '2013-12-12T16:00:00.000Z', '$lt': ...
You can use new Date('2013-12-12T16:00:00.000Z') in node.js; new is a must, because Date() is already use to return date string. ISODate is concepted in mongodb, you can use it in mongodb console, but it can be different for different programming language.
MongoDB
20,561,381
76
To what extent are 'lost data' criticisms still valid of MongoDB? I'm referring to the following: 1. MongoDB issues writes in unsafe ways by default in order to win benchmarks If you don't issue getLastError(), MongoDB doesn't wait for any confirmation from the database that the command was processed. This intro...
Note on Context: This question was asked in 2012, but still sees traffic and votes to this day. The original answer was specifically to refute a particular post that was popular at the time of the question. Things have changed (and continue to change) massively since this answer was written. MongoDB has certainly beco...
MongoDB
10,560,834
76
I have a document structured like this: { _id:"43434", heroes : [ { nickname : "test", items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }, ] } Can I $set the second element of the items array of the embedded object in array heros with nickname "test" ? Result: { _id:"...
You need to make use of 2 concepts: mongodb's positional operator and simply using the numeric index for the entry you want to update. The positional operator allows you to use a condition like this: {"heroes.nickname": "test"} and then reference the found array entry like so: {"heroes.$ // <- the dollar represents t...
MongoDB
10,432,677
76
I've been using mongo and script files like this: $ mongo getSimilar.js I would like to pass an argument to the file: $ mongo getSimilar.js apples And then in the script file pick up the argument passed in. var arg = $1; print(arg);
Use --eval and use shell scripting to modify the command passed in. mongo --eval "print('apples');" Or make global variables (credit to Tad Marshall): $ cat addthem.js printjson( param1 + param2 ); $ ./mongo --nodb --quiet --eval "var param1=7, param2=8" addthem.js 15
MongoDB
10,114,355
76
Let's say I have the following documents Article { Comment: embedMany } Comment { Reply: embedMany } Reply { email: string, ip: string } I want to make a query that selects distinct Reply.ip where Reply.email = xxx Something like this, only it doesn't work.. db.Article.find("Comment.Reply.email" : "xxx").distinct("C...
Distinct query in mongo with condition works like this db.Article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"}) not other way around EDIT: I understand the problem now, inorder to match/filter subdocuments we need to use $elemMatch operator, like this db.Article.distinct("Comment.Reply.ip",{Commen...
MongoDB
7,419,986
76