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 wonder wether there is a solution (or a need for) an ORM with Graph-Database (f.e. Neo4j). I'm tracking relationships (A is related to B which is related to A via C etc., thus constructing a large graph) of entities (including additional attributes for those entities) and need to store them in a DB, and i think a gra...
Shameless plug... there is also my own ORM which you may also want to checkout: https://github.com/robinedwards/neomodel It's built on top of py2neo, using cypher and rest API calls under hood, i.e no dependency on gremlin.
Neo4j
8,356,626
20
I have a general question about modeling in a graph database that I just can't seem to wrap my head around. How do you model this type of relationship: "Newton invented Calculus"? In a simple graph, you could model it like this: Newton (node) -> invented (relationship) -> Calculus (node) ...so you'd have a bunch of "i...
Some of these things, such as invention_date, can be stored as properties on the edges as in most graph databases edges can have properties in the same way that vertexes can have properties. For example you could do something like this (code follows TinkerPop's Blueprints): Graph graph = new Neo4jGraph("/tmp/my_graph")...
Neo4j
7,536,142
20
How can i inject a properties file containing a Map to be used as additional constructor arg using the field. With a Map being loaded from a properties file the bean is currently setup using: <bean id="graphDbService" class="org.neo4j.kernel.EmbeddedGraphDatabase" init-method="enableRemoteShell" destroy-method="s...
Something like this: <bean id="configuration" class="org.neo4j.kernel.EmbeddedGraphDatabase" factory-method="loadConfigurations"> <constructor-arg value="neo4j_config.props"/> </bean> <bean id="graphDbService" class="org.neo4j.kernel.EmbeddedGraphDatabase" init-method="enableRemoteShell" destroy-method=...
Neo4j
3,466,437
20
Is there a .NET version/binding for Neo4j? It looks like exactly what I want, but I'm working in C# on .NET. Thanks
I think you best bet at the moment is to use the REST server. There's a blog post with a proof of concept .NET client: Neo4j .NET Client over HTTP using REST and json. Update: Now there's actually two different .Net Neo4j REST clients: Neo4RestNet Neo4jRestSharp
Neo4j
2,720,271
20
According to https://neo4j-contrib.github.io/neo4j-apoc-procedures/, one only needs to download the binary jar from http://github.com/neo4j-contrib/neo4j-apoc-procedures/releases/3.1.0.3 to place into the folder "Neo4j CE 3.1.1\plugins". I did so. However, I was unable to call "call apoc.help("apoc")" from the http://...
I'm using Red Hat Linux specifically Oracle-7 and here is how I got it working Download the apoc-<version>.jar into the /var/lib/neo4j/plugins directory chown neo4j:neo4j apoc-<version>.jar chmod 755 apoc-<version>.jar Open the neo4j.conf at /etc/neo4j/neo4j.conf and replace the line #dbms.security.procedures.whitelis...
Neo4j
42,740,355
19
When you add a Node to Neo4j and you access your graph via the Neo4j Browser, the Node that was created is displayed (as a circle) and the Name property is outputted as the primary property for the Node. You can tell which Nodes are which by the name field, without having to click on them. If you do not specify a Name ...
This is quite simple to achieve. At the top you see the Label of the node (Type of node), for example :User. At the bottom of that panel, you should be able to see the Label (User) along with color and size options. At the right corner there should be an arrow "<" Click this to expand your options There should b...
Neo4j
37,495,220
19
What is the best way to cleanup the graph from all nodes and relationships via Cypher? At http://neo4j.com/docs/stable/query-delete.html#delete-delete-a-node-and-connected-relationships the example MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r has the note: This query isn’t for deleting large amounts of data So, is...
As you've mentioned the most easy way is to stop Neo4j, drop the data/graph.db folder and restart it. Deleting a large graph via Cypher will be always slower but still doable if you use a proper transaction size to prevent memory issues (remember transaction are built up in memory first before they get committed). Typ...
Neo4j
29,711,757
19
As far as I understand it the IDs given by Neo4j (ID(node)) are unstable and behave somewhat like row numbers in SQL. Since IDs are mostly used for relations in SQL and these are easily modeled in Neo4j, there doesn't seem to be much use for IDs, but then how do you solve retrieval of specific nodes? Having a REST API ...
Neo4j internal ids are a bit more stable than sql row id's as they will never change during a transaction for e.g. And indeed exposing them for external usage is not recommended. I know there are some intentions at Neo internals to implement such a feature. Basically people tend to use two solutions for this : Using a...
Neo4j
29,434,020
19
SSDs are commonplace now; Amazon EBS is backed by SSDs, and hence most of the cloud databases now also run on SSDs (Heroku PostgreSQL, etc.). Databases and related architectures were traditionally designed with the idea the random access is bad - this is no longer the case with SSDs. How do SSDs effect the following? ...
First, SSDs don't make random access free. Just cheaper. In particular, random writes remain very expensive, though that's mitigated in small random writes by a durable write-back cache. WAL would be very expensive on SSDs if the SSD truly flushed it to the underlying media - but it doesn't. It accumulates it in write-...
Neo4j
26,640,769
19
I was wondering how WHERE id(n) = id compares to START n = node(id) as most of the time I do not select nodes by id (at least in number of code appearances) and therefore like to do it always in the match
The two statements are identical. START is the syntax to be used in Neo4j 1.x. From Neo4j 2.0 the MATCH variant should be preferred, maybe START will get deprecated at some future release.
Neo4j
21,651,479
19
I am working on windows. I have created a text file of Cypher query using notepad. How can I run the query in the file using Neo4jShell or Neo4j web interface console.
On Debian/Ubuntu or any *nix installations, use the following from terminal: $ neo4j-shell -c < path-to-cypher-query-file.cql Note that each cypher query in the file must end in a semicolon and must be separated by a blank line from the other query. Also, the .cql ending (file format) is not mandatory.
Neo4j
17,462,306
19
I'm new to MongoDB Compass tool and am trying to update a field in my collection. Please can someone suggest where the update query must be written. Could find no options or panes in the tool to write custom queries be it selection / updation for that matter. In the Default Window only the selection/projection/restrict...
In the latest version, there is a "_MongoSH" in the bottom left corner of the window. Thx to @Boštjan Pišler for the hint about a new feature. Old answer: I had the same issue, it looks like a simple feature to implement (since document updates are possible) but... AFAIK there is no such option in compass, you can do i...
MongoDB
49,110,169
120
I'm preparing a database creation script in Node.js and Mongoose. How can I check if the database already exists, and if so, drop (delete) it using Mongoose? I could not find a way to drop it with Mongoose.
There is no method for dropping a collection from mongoose, the best you can do is remove the content of one : Model.remove({}, function(err) { console.log('collection removed') }); But there is a way to access the mongodb native javascript driver, which can be used for this mongoose.connection.collections['colle...
MongoDB
10,081,452
120
I have collection that contains documents with below schema. I want to filter/find all documents that contain the gender female and aggregate the sum of brainscore. I tried the below statement and it shows a invalid pipeline error. db['!all'].aggregate({ $and: [ {'GENDER' : 'F'} , {'DOB' : { $gte : 19400801, $lte : 20...
You have to use $match: db['!all'].aggregate([ {$match: {'GENDER': 'F', 'DOB': { $gte: 19400801, $lte: 20131231 } } }, {$group: {_id: "$GENDER", totalscore:{ $sum: "$BRAINSCORE"}}} ]) Outputs: { "_id" : "F", "totalscore" : 109 }
MongoDB
25,436,630
119
I cannot manually or automatically populate the creator field on a newly saved object ... the only way I can find is to re-query for the objects I already have which I would hate to do. This is the setup: var userSchema = new mongoose.Schema({ name: String, }); var User = db.model('User', userSchema); var bookSch...
You should be able to use the Model's populate function to do this: http://mongoosejs.com/docs/api.html#model_Model.populate In the save handler for book, instead of: book._creator = user; you'd do something like: Book.populate(book, {path:"_creator"}, function(err, book) { ... }); Probably too late an answer to hel...
MongoDB
13,525,480
119
I followed the MongoDb Docs to setup my first MongoDb, When I start MongoDB using the command C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe I get the following error exception in initAndListen: 29 Data directory C:\data\db\ not found., terminating shutdown: going to close listening sockets... shutdown: going to ...
MongoDB needs a folder to store the database. Create a C:\data\db\ directory: mkdir C:\data\db and then start MongoDB: C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe Sometimes C:\data\db folder already exists due to previous installation. So if for this reason mongod.exe does not work, you may delete all the cont...
MongoDB
41,420,466
118
I need to search an ObjectId with python using pymongo but I always get an error. import pymongo from pymongo import MongoClient from pymongo import ObjectId gate = collection.find({'_id': ObjectId(modem["dis_imei"])}) Any ideas how to search?
I use pymongo 2.4.1. from bson.objectid import ObjectId [i for i in dbm.neo_nodes.find({"_id": ObjectId(obj_id_to_find)})]
MongoDB
16,073,865
118
I'm using Mongoose, MongoDB, and Node.js. I would like to define a schema where one of its fields is a date\timestamp. I would like to use this field in order to return all of the records that have been updated in the last 5 minutes. Due to the fact that in Mongoose I can't use the Timestamp() method, I understand that...
Edit - 20 March 2016 Mongoose now support timestamps for collections. Please consider the answer of @bobbyz below. Maybe this is what you are looking for. Original answer Mongoose supports a Date type (which is basically a timestamp): time : { type : Date, default: Date.now } With the above field definition, any time ...
MongoDB
10,006,218
118
I'm trying to connect to my mongoDB server via the connection string given to me by mongo: "mongodb+srv://david:password@cluster0-re3gq.mongodb.net/test?retryWrites=true" In my code I am calling the connection through mongoose like this (obviously putting in my password): const mongoose = require('mongoose'); const db...
I had the same problem, and in my case, the answer was as simple as removing the angle brackets "<"and ">" around <password>. I had been trying: my_login_id:<my_password>, when it should have been my_login_id:my_password.
MongoDB
55,695,565
117
How does one use Mongo Compass and search by ObjectID? I've been searching for the documentation for this but haven't been successful with anything. I have tried: { "_id" : "58f8085dc1840e050034d98f" } { "$oid" : "58f8085dc1840e050034d98f" } { "id" : "58f8085dc1840e050034d98f" } None of those seem to work and it's g...
UPDATE Newer versions of Compass now support querying ObjectId similar to how they would be queried via the mongo shell (the $oid syntax will not work in these newer versions): {_id: ObjectId('58f8085dc1840e050034d98f')} If you're using an older version before 1.10.x you, enter the following into the query box: {"_id"...
MongoDB
43,525,523
117
Where is this error coming from? I am not using ensureIndex or createIndex in my Nodejs application anywhere. I am using yarn package manager. Here is my code in index.js import express from 'express'; import path from 'path'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; import Promise from 'b...
The issue is that mongoose still uses collection.ensureIndex and should be updated by them in the near future. To get rid of the message you can downgrade by using version 5.2.8 in your package.json (and delete any caches, last resort is to uninstall it the install it with npm install mongoose@5.2.8): "mongoose": "^...
MongoDB
51,960,171
116
I'm installing MongoDB on an Ubuntu 14.04 machine, using the instructions at: https://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ So I run: sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 And then: echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse...
Update all expired keys from Ubuntu key server in one command: sudo apt-key list | \ grep "expired: " | \ sed -ne 's|pub .*/\([^ ]*\) .*|\1|gp' | \ xargs -n1 sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys Command explanation: sudo apt-key list - lists all keys installed in the system; grep ...
MongoDB
34,733,340
116
I would like to drop into the mongo shell in the terminal on my MacBook. However, I'm interested in connecting to a Mongo instance that is running in the cloud (compose.io instance via Heroku addon). I have the name, password, host, port, and database name from the MongoDB URI: mongodb://username:password@somewhere.m...
You are probably connecting fine but don't have sufficient privileges to run show dbs. You don't need to run the db.auth if you pass the auth in the command line: mongo somewhere.mongolayer.com:10011/my_database -u username -p password Once you connect are you able to see collections? > show collections If so all is ...
MongoDB
26,813,912
116
If I have a mongo instance running, how can I check what port numbers it is listening on from the shell? I thought that db.serverStatus() would do it but I don't see it. I see this "connections" : { "current" : 3, "available" : 816 Which is close... but no. Suggestions? I've read the docs and can't seem to fin...
You can do this from the Operating System shell by running: sudo lsof -iTCP -sTCP:LISTEN | grep mongo
MongoDB
9,346,431
116
I'm trying to select a document by id I've tried: collection.update({ "_id": { "$oid": + theidID } } collection.update({ "_id": theidID } collection.update({ "_id.$oid": theidID }} Also tried: collection.update({ _id: new ObjectID(theidID ) } This gives me an error 500... var mongo = require('mongodb') var BSON = m...
var mongo = require('mongodb'); var o_id = new mongo.ObjectID(theidID); collection.update({'_id': o_id});
MongoDB
4,902,569
116
Bit of an odd one on query performance... I need to run a query which does a total count of documents, and can also return a result set that can be limited and offset. So, I have 57 documents in total, and the user wants 10 documents offset by 20. I can think of 2 ways of doing this, first is query for all 57 documents...
I suggest you to use 2 queries: db.collection.count() will return total number of items. This value is stored somewhere in Mongo and it is not calculated. db.collection.find().skip(20).limit(10) here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast to...
MongoDB
13,935,733
115
I am kind of new to mac as well as mongodb. I have a weird doubt, accessing the database created using mongodb on mac? I know, in windows there is a folder called c:\data\db, where my database files are stored. How and where in mac, the database is stored. I remember doing something like sudo mkdir -p /data/db sudo ch...
If MongoDB is installed on macOS via Homebrew, the default data directory depends on the type of processor in the system. Intel Processor Apple Silicon Processor (M1, M2, etc) Data Directory /usr/local/var/mongodb /opt/homebrew/var/mongodb Configuration file /usr/local/etc/mongod.conf /opt/homebrew/etc/mongo...
MongoDB
13,827,915
115
I want to combine two OR-queries with AND in Monoose, like in this SQL statement: SELECT * FROM ... WHERE (a = 1 OR b = 1) AND (c=1 OR d=1) I tried this in a NodeJS module which only gets the model object from the main application: /********** Main application ***********/ var query = MyModel.find({}); myModule1.addCo...
It's probably easiest to create your query object directly as: Test.find({ $and: [ { $or: [{a: 1}, {b: 1}] }, { $or: [{c: 1}, {d: 1}] } ] }, function (err, results) { ... } But you can also use the Query#and helper that's available in recent 3.x Mongoose releases: Test.fin...
MongoDB
13,272,824
115
It seems mongo does not allow insertion of keys with a dot (.) or dollar sign ($) however when I imported a JSON file that contained a dot in it using the mongoimport tool it worked fine. The driver is complaining about trying to insert that element. This is what the document looks like in the database: { "_id": { ...
MongoDB doesn't support keys with a dot in them so you're going to have to preprocess your JSON file to remove/replace them before importing it or you'll be setting yourself up for all sorts of problems. There isn't a standard workaround to this issue, the best approach is too dependent upon the specifics of the situat...
MongoDB
12,397,118
115
I am using mongoose (node), what is the best way to output id instead of _id?
Given you're using Mongoose, you can use 'virtuals', which are essentially fake fields that Mongoose creates. They're not stored in the DB, they just get populated at run time: // Duplicate the ID field. Schema.virtual('id').get(function(){ return this._id.toHexString(); }); // Ensure virtual fields are serialised...
MongoDB
7,034,848
115
The three types of NoSQL databases I've read about is key-value, column-oriented, and document-oriented. Key-value is pretty straight forward - a key with a plain value. I've seen document-oriented databases described as like key-value, but the value can be a structure, like a JSON object. Each "document" can have all,...
The main difference is that document stores (e.g. MongoDB and CouchDB) allow arbitrarily complex documents, i.e. subdocuments within subdocuments, lists with documents, etc. whereas column stores (e.g. Cassandra and HBase) only allow a fixed format, e.g. strict one-level or two-level dictionaries.
MongoDB
7,565,012
114
I tried to run it and it said an error like the title. and this is my code: const URI = process.env.MONGODB_URL; mongoose.connect(URI, { useCreateIndex: true, useFindAndModify: false, useNewUrlParser: true, useUnifiedTopology: true }, err => { if(err) throw err; console.log('Connected to MongoDB!...
From the Mongoose 6.0 docs: useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.
MongoDB
68,958,221
113
I have Category model: Category: ... articles: [{type:ObjectId, ref:'Article'}] Article model contains ref to Account model. Article: ... account: {type:ObjectId, ref:'Account'} So, with populated articles Category model will be: { //category articles: //this field is populated [ { account: ...
Firstly, update mongoose 3 to 4 & then use the simplest way for deep population in mongoose as shown below: Suppose you have Blog schema having userId as ref Id & then in User you have some review as ref Id for schema Review. So Basically, you have three schemas: Blog User Review And, you have to query from blog, whi...
MongoDB
18,867,628
113
Specifically, I want to print the results of a mongodb find() to a file. The JSON object is too large so I'm unable to view the entire object with the shell window size.
The shell provides some nice but hidden features because it's an interactive environment. When you run commands from a javascript file via mongo commands.js you won't get quite identical behavior. There are two ways around this. (1) fake out the shell and make it think you are in interactive mode $ mongo dbname << EOF ...
MongoDB
13,104,800
113
In the following example, assume the document is in the db.people collection. How to remove the 3rd element of the interests array by it's index? { "_id" : ObjectId("4d1cb5de451600000000497a"), "name" : "dannie", "interests" : [ "guitar", "programming", "gadgets", "re...
There is no straight way of pulling/removing by array index. In fact, this is an open issue http://jira.mongodb.org/browse/SERVER-1014 , you may vote for it. The workaround is using $unset and then $pull: db.lists.update({}, {$unset : {"interests.3" : 1 }}) db.lists.update({}, {$pull : {"interests" : null}}) Update:...
MongoDB
4,588,303
113
Is there an easy way to get the ID (ObjectID) of the last inserted document of a mongoDB instance using the Java driver?
I just realized you can do this: BasicDBObject doc = new BasicDBObject( "name", "Matt" ); collection.insert( doc ); ObjectId id = (ObjectId)doc.get( "_id" );
MongoDB
3,338,999
113
I've just arrived to Node.js and see that there are many libs to use with the MongoDB, the most popular seem to be these two: (mongoose and mongodb). Can I get pros and cons of those extensions? Are there better alternatives to these two? Edit: Found a new library that seems also interesting node-mongolian and is "Mong...
Mongoose is higher level and uses the MongoDB driver (it's a dependency, check the package.json), so you'll be using that either way given those options. The question you should be asking yourself is, "Do I want to use the raw driver, or do I need an object-document modeling tool?" If you're looking for an object model...
MongoDB
9,232,562
112
I would like to know if there're a command to drop every databases from my MongoDB? I know if I want to drop only one datatable, I just need to type the name of the database like the code below but I dont want to have to specify it. mongo DB_NAME --eval 'db.dropDatabase();'
you can create a javascript loop that do the job and then execute it in the mongoconsole. var dbs = db.getMongo().getDBNames() for(var i in dbs){ db = db.getMongo().getDB( dbs[i] ); print( "dropping db " + db.getName() ); db.dropDatabase(); } save it to dropall.js and then execute: mongo dropall.js
MongoDB
6,376,436
112
I want to set one of my fields as primary key. I am using MongoDB as my NoSQL.
_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field. Additional info: http://www.mongodb.org/display/DOCS/BSON Hope it helps.
MongoDB
3,298,963
112
2 days old with Mongo and I have a SQL background so bear with me. As with mysql, it is very convenient to be in the MySQL command line and output the results of a query to a file on the machine. I am trying to understand how I can do the same with Mongo, while being in the shell I can easily get the output of a query ...
AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File However, you can log all the shell session if you invoked the shell with tee command: $ mongo | tee file.txt MongoDB shell version: 2.4.2 connecting to: test > printjson({...
MongoDB
22,565,231
109
i'm running mongo 1.8.2 and trying to see how to cleanly shut it down on Mac. on our ubuntu servers i can shutdown mongo cleanly from the mongo shell with: > use admin > db.shutdownServer() but on my Mac, it does not kill the mongod process. the output shows that it 'should be' shutdown but when i ps -ef | grep mongo...
It's probably because launchctl is managing your mongod instance. If you want to start and shutdown mongod instance, unload that first: launchctl unload -w ~/Library/LaunchAgents/org.mongodb.mongod.plist Then start mongod manually: mongod -f path/to/mongod.conf --fork You can find your mongod.conf location from ~/Lib...
MongoDB
8,495,293
109
Background I'm prototyping a conversion from our RDBMS database to MongoDB. While denormalizing, it seems as if I have two choices, one which leads to many (millions) of smaller documents or one which leads to fewer (hundreds of thousands) large documents. If I could distill it down to a simple analog, it would be the ...
You'll definitely need to optimize for the queries you're doing. Here's my best guess based on your description. You'll probably want to know all Credit Cards for each Customer, so keep an array of those within the Customer Object. You'll also probably want to have a Customer reference for each Payment. This will keep ...
MongoDB
3,038,703
109
The main collection is retailer, which contains an array for stores. Each store contains an array of offers (you can buy in this store). This offers array has an array of sizes. (See example below) Now I try to find all offers, which are available in the size L. { "_id" : ObjectId("56f277b1279871c20b8b4567"), "...
So the query you have actually selects the "document" just like it should. But what you are looking for is to "filter the arrays" contained so that the elements returned only match the condition of the query. The real answer is of course that unless you are really saving a lot of bandwidth by filtering out such detail...
MongoDB
36,229,123
108
I am using MongoDB 2.2.2 for 32-bit Windows7 machine. I have a complex aggregation query in a .js file. I need to execute this file on the shell and direct the output to a CSV file. I ensure that the query returns a "flat" json (no nested keys), so it is inherently convertible to a neat csv. I know about load() and ev...
I know this question is old but I spend an hour trying to export a complex query to csv and I wanted to share my thoughts. First I couldn't get any of the json to csv converters to work (although this one looked promising). What I ended up doing was manually writing the csv file in my mongo script. This is a simple v...
MongoDB
14,478,304
108
This error happens when I tried to update upsert item: Updating the path 'x' would create a conflict at 'x'
Field should appear either in $set, or in $setOnInsert. Not in both.
MongoDB
50,947,772
107
I'm sure I'm missing something very basic in MongoDB queries, can't seem to get this simple condition. Consider this collection > db.tests.find() { "_id" : ObjectId("..."), "name" : "Test1" , "deleted" : true} { "_id" : ObjectId("..."), "name" : "Test2" , "deleted" : false} { "_id" : ObjectId("..."), "name" : "Test3" ...
db.tests.find({deleted: {$ne: true}}) Where $ne stands for "not equal". (Documentation on mongodb operators)
MongoDB
18,837,486
107
I like to to go find a user in mongoDb by looking for a user called value. The problem with: username: 'peter' is that i dont find it if the username is "Peter", or "PeTER".. or something like that. So i want to do like sql SELECT * FROM users WHERE username LIKE 'peter' Hope you guys get what im askin for? Short: 'f...
For those that were looking for a solution here it is: var name = 'Peter'; model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) { //Do your action here.. });
MongoDB
9,824,010
107
Is there a way to see a list of indices on a collection in mongodb in shell? i read through http://www.mongodb.org/display/DOCS/Indexes but i dont see anything
From the shell: db.test.getIndexes() For shell help you should try: help; db.help(); db.test.help();
MongoDB
2,789,865
107
I am new to MongoDB. I am trying to install MongoDb 3.0 on Ubuntu 13.0 LTS, which is a VM on Windows 7 Host. I have installed MongoDB successfully (packages etc.), but when I execute the command sudo service mongod start, I get the following error in the "/var/log/mongodb/mongod.log" log file. Can anyone help me unders...
I have fixed this issue myself, by deleting the mongodb-27017.sock file . I ran the service after deleting this file, which worked fine. However, I am still not sure the root cause of the issue. The output of the command ls - lat /tmp/mongodb-27017.sock is now srwx------ 1 mongodb nogroup 0 Apr 23 06:24 /tmp/mongodb-27...
MongoDB
29,813,648
106
I am making a database for video games, each containing elements like name, genre, and and image of the game. Is it possible to put images into a json object for the db? If not is there a way around this?
I can think of doing it in two ways: 1. Storing the file in file system in any directory (say dir1) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate ...
MongoDB
34,485,420
104
users { "_id":"12345", "admin":1 }, { "_id":"123456789", "admin":0 } posts { "content":"Some content", "owner_id":"12345", "via":"facebook" }, { "content":"Some other content", "owner_id":"123456789", "via":"facebook" } Here is a sample from my mongodb. I want to get all the posts which has "via" attribute...
You can use $lookup ( multiple ) to get the records from multiple collections: Example: If you have more collections ( I have 3 collections for demo here, you can have more than 3 ). and I want to get the data from 3 collections in single object: The collection are as: db.doc1.find().pretty(); { "_id" : ObjectId("5...
MongoDB
6,502,541
104
I am using pymongo to query for all items in a region (actually it is to query for all venues in a region on a map). I used db.command(SON()) before to search in a spherical region, which can return me a dictionary and in the dictionary there is a key called results which contains the venues. Now I need to search in a ...
The find method returns a Cursor instance, which allows you to iterate over all matching documents. To get the first document that matches the given criteria, you need to use find_one. The result of find_one is a dictionary. You can always use the list constructor to return a list of all the documents in the collection...
MongoDB
28,968,660
103
I created a dump with mongodump on computer A (ubuntu 12.04 server). I moved it to computer B (ubuntu 12.04 server) and typed: mongorestore -db db_name --drop db_dump_path It failed and it reported: connected to: 127.0.0.1 terminate called after throwing an instance of 'std::runtime_error' what(): locale::facet...
On my distro "locale-gen" was not installed and it turned out all I had to do is set the LC_ALL environment variable. so the following command fixed it: export LC_ALL="en_US.UTF-8" hopefully it will help someone else...
MongoDB
19,100,708
103
At the moment I use save to add a single document. Suppose I have an array of documents that I wish to store as single objects. Is there a way of adding them all with a single function call and then getting a single callback when it is done? I could add all the documents individually but managing the callbacks to wo...
Mongoose does now support passing multiple document structures to Model.create. To quote their API example, it supports being passed either an array or a varargs list of objects with a callback at the end: Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { if (err) // ....
MongoDB
10,266,512
103
The two types of objects seem to be so close to one another that having both feels redundant. What is the point of having both schemas and models?
EDIT: Although this has been useful for many people, as mentioned in the comments it answers the "how" rather than the why. Thankfully, the why of the question has been answered elsewhere also, with this answer to another question. This has been linked in the comments for some time but I realise that many may not get t...
MongoDB
9,127,174
103
I've been searching the web looking for best practices for configuring MongoOptions for the MongoDB Java driver and I haven't come up with much other than the API. This search started after I ran into the "com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db connection" error and by increasing the connect...
Updated to 2.9 : autoConnectRetry simply means the driver will automatically attempt to reconnect to the server(s) after unexpected disconnects. In production environments you usually want this set to true. connectionsPerHost are the amount of physical connections a single Mongo instance (it's singleton so you usually...
MongoDB
6,520,439
103
I am trying to distribute a set of connected applications running in several linked containers that includes a mongo database that is required to: be distributed containing some seed data; allow users to add additional data. Ideally the data will also be persisted in a linked data volume container. I can get the data...
I do this using another docker container whose only purpose is to seed mongo, then exit. I suspect this is the same idea as ebaxt's, but when I was looking for an answer to this, I just wanted to see a quick-and-dirty, yet straightforward, example. So here is mine: docker-compose.yml mongodb: image: mongo ports: ...
MongoDB
31,210,973
102
I have a hard time believing this question hasn't been asked and answered somewhere already, but I can't find any trace of it. I have a MongoDB aggregation query that needs to group by a boolean: the existence of another field. For example let's start with this collection: > db.test.find() { "_id" : ObjectId("53fbede62...
I solved the same problem just last night, this way: > db.test.aggregate({$group:{_id:{$gt:["$field", null]}, count:{$sum:1}}}) { "_id" : true, "count" : 2 } { "_id" : false, "count" : 2 } See http://docs.mongodb.org/manual/reference/bson-types/#bson-types-comparison-order for a full explanation of how this works. Add...
MongoDB
25,497,150
102
I'm using MongoDB to be my database. i have a data: { _id : '123' friends: [ {name: 'allen', emails: [{email: '11111', using: 'true'}]} ] } now, i wanna to modify user's friends' emails ' email, whose _id is '123' i write like this: db.users.update ({_id: '123'}, {$set: {"friends.0.emails.$.email" : '...
You need to use the Dot Notation for the arrays. That is, you should replace the $ with the zero-based index of the element you're trying to update. For example: db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} }); will update the first email of the first friend, and db.users.update ({_id...
MongoDB
19,603,542
102
Env: MongoDB (3.2.0) with Mongoose Collection: users Text Index creation: BasicDBObject keys = new BasicDBObject(); keys.put("name","text"); BasicDBObject options = new BasicDBObject(); options.put("name", "userTextSearch"); options.put("unique", Boolean.FALSE); options.put("background", Boolean.TRUE...
As at MongoDB 3.4, the text search feature is designed to support case-insensitive searches on text content with language-specific rules for stopwords and stemming. Stemming rules for supported languages are based on standard algorithms which generally handle common verbs and nouns but are unaware of proper nouns. Ther...
MongoDB
44,833,817
101
I'm pretty new to Mongoose and MongoDB in general so I'm having a difficult time figuring out if something like this is possible: Item = new Schema({ id: Schema.ObjectId, dateCreated: { type: Date, default: Date.now }, title: { type: String, default: 'No Title' }, description: { type: String, default: ...
With a modern MongoDB greater than 3.2 you can use $lookup as an alternate to .populate() in most cases. This also has the advantage of actually doing the join "on the server" as opposed to what .populate() does which is actually "multiple queries" to "emulate" a join. So .populate() is not really a "join" in the sense...
MongoDB
11,303,294
101
Can anyone give example use cases of when you would benefit from using Redis and MongoDB in conjunction with each other?
Redis and MongoDB can be used together with good results. A company well-known for running MongoDB and Redis (along with MySQL and Sphinx) is Craiglist. See this presentation from Jeremy Zawodny. MongoDB is interesting for persistent, document oriented, data indexed in various ways. Redis is more interesting for volati...
MongoDB
10,696,463
101
i found this error when trying to run mongodb. I install it via homebrew. Please assist Agungs-MacBook-Pro:~ agungmahaputra$ mongod 2017-12-26T15:31:15.911+0700 I CONTROL [initandlisten] MongoDB starting : pid=5189 port=27017 dbpath=/data/db 64-bit host=Agungs-MacBook-Pro.local 2017-12-26T15:31:15.911+0700 I CONTROL ...
You can kill the previous mongod instance and start the new one. To kill the previous mongod instance, first search for a list of tasks running on your machine by typing, sudo lsof -iTCP -sTCP:LISTEN -n -P Search for mongod COMMAND and its PID and type, sudo kill <mongo_command_pid> Now start your mongod instance by ...
MongoDB
47,975,929
99
In MongoDB, is it possible to dump a database and restore the content to a different database? For example like this: mongodump --db db1 --out dumpdir mongorestore --db db2 --dir dumpdir But it doesn't work. Here's the error message: building a list of collections to restore from dumpdir dir don't know what to do wit...
You need to actually point at the "database name" container directory "within" the output directory from the previous dump: mongorestore -d db2 dumpdir/db1 And usually just <path> is fine as a positional argument rather than with -dir which would only be needed when "out of position" i.e "in the middle of the argument...
MongoDB
36,321,899
99
What is the command to show the current db in the MongoDB shell? (I failed to find it on Google)
Found it by guessing :) Simply: db
MongoDB
16,004,182
99
I am using a case insensitive search in Mongo, something similar to https://stackoverflow.com/q/5500823/1028488. ie. I am using a regex with options i. But I am having trouble restricting the regex to just that word, it performs more like a 'Like' in SQL eg: if I use query like {"SearchWord" : { '$regex' : 'win', $opti...
You can Use $options => i for case insensitive search. Giving some possible examples required for string match. Exact case insensitive string db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}}) Contains string db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}}) Start with string db.col...
MongoDB
8,246,019
99
So I have an embedded document that tracks group memberships. Each embedded document has an ID pointing to the group in another collection, a start date, and an optional expire date. I want to query for current members of a group. "Current" means the start time is less than the current time, and the expire time is gr...
Just thought I'd update in-case anyone stumbles across this page in the future. As of 1.5.3, mongo now supports a real $or operator: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as: {$or: [{expires: {$gte: new Date...
MongoDB
2,008,032
99
I'm receiving the following warning from mongodb about THP 2015-03-06T21:01:15.526-0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2015-03-06T21:01:15.526-0800 I CONTROL [initandlisten] ** We suggest setting it to 'never' But I did manage to turned THP off ma...
Official MongoDB documentation gives several solutions for this issue. You can also try this solution, which worked for me: Note: Try official documentation directives if MongoDB version is greater than 3.0 Open /etc/init.d/mongod file. (if no such file you might check /etc/init.d/mongod, /etc/init/mongod.conf files ...
MongoDB
28,911,634
98
I'm trying to find all documents that do not contain at least one document with a specific field value. For example here is a sample collection: { _id : 1, docs : [ { foo : 1, bar : 2}, { foo : 3, bar : 3} ] }, { _id : 2, docs : [ { foo : 2, bar : 2}...
Using $nin will work, but you have the syntax wrong. It should be: db.collection.find({'docs.foo': {$nin: [1]}})
MongoDB
16,221,599
98
I am following the tutorials at docs.mongodb.org, I have completed the first tutorial which was to install mongodb on a Windows machine. I am now at the second stage which is getting started with mongodb development. I am stuck at the first stage of this section which instructs me to type mongo into a system prompt. Wh...
You need to add Mongo's bin folder to the "Path" Environment Variable Here's how on Windows 10: Find Mongo's bin folder. If you're not sure where it is, it's probably in C:\Program Files\MongoDB\Server\3.4\ 3.4 was the latest stable version at the time, this will be different for you probably. It should look like thi...
MongoDB
15,053,893
98
Using this modified example from the Rails guides, how does one model a relational "has_many :through" association using mongoid? The challenge is that mongoid does not support has_many :through as ActiveRecord does. # doctor checking out patient class Physician < ActiveRecord::Base has_many :appointments has_many ...
Mongoid doesn't have has_many :through or an equivalent feature. It would not be so useful with MongoDB because it does not support join queries so even if you could reference a related collection via another it would still require multiple queries. https://github.com/mongoid/mongoid/issues/544 Normally if you have a m...
MongoDB
7,000,605
98
What are some GUIs to use with Mongo, and what features do they offer? I'm looking for facts here, not opinions on which interface is best.
Official List from MongoDB http://www.mongodb.org/display/DOCS/Admin+UIs Web Based For PHP, I'd recommend Rock Mongo. Solid, lots of great features, easy setup. http://rockmongo.com/ If you don't want to install anything ... you can use MongoHQ's web interface (even if you your MongoDB isn't on MongoHQ.) https://mongoh...
MongoDB
4,269,688
98
I am currently trying out this tutorial for node express with mongodb https://medium.com/@sunnykay/docker-development-workflow-node-express-mongo-4bb3b1f7eb1e the first part works fine where to build the docker-compose.yml it works totally fine building it locally so I tried to tag it and push into my dockerhub to lear...
I found out, I was being stupid. I didn't need to run docker-compose build I can just directly run docker-compose up since then it'll pull the images down, the build is just to build locally
MongoDB
47,615,495
97
I am using Mongoose aggregation (MongoDB version 3.2). I have a field users which is an array. I want to $project first item in this array to a new field user. I tried { $project: { user: '$users[0]', otherField: 1 }}, { $project: { user: '$users.0', otherField: 1 }}, { $project: { user...
Update: Starting from v4.4 there is a dedicated operator $first: { $project: { user: { $first: "$users" }, otherField: 1 }}, It's a syntax sugar to the Original answer: You can use arrayElemAt: { $project: { user: { $arrayElemAt: [ "$users", 0 ] }, otherField: 1 }},
MongoDB
39,196,537
96
I read the documentation in the MongoDb and I used a simple proves and I only look that: Push is sorting the array but addtoSet isn't it. For me visually is the same, I don't know the difference. Could anybody explain me the difference? Another think if it could be in spanish or in a simple english, i'll aprecite it.
$addToSet do not add the item to the given field if it already contains it, on the other hand $push will add the given object to field whether it exists or not. {_id: "docId", items: [1, 2]} db.items.update({_id:"docId"}, {$addToSet:{items: 2}}); // This won't update the document as it already contains 2 db.items.updat...
MongoDB
27,248,556
96
I recently installed mongodb-2.6.0 with Homebrew. After successfully installed, I tried to connect using the mongo command. I am receiving the following errors which do not allow me to connect: Failed to connect to 127.0.0.1:27017, reason: errno:61 Connection refused Error: couldn't connect to server 127.0.0.1:27017 (...
It can happen when the mongodb service is not running on the mac. To start it, I tried brew services start mongodb and it worked. Edit: According to the discussion on this PR on homebrew: https://github.com/Homebrew/homebrew/issues/30628 brew services is deprecated, I looked around on SO and found these answers now an...
MongoDB
23,418,134
96
I am trying to migrate from sqlalchemy(SQlite) to using mongodb. I would like schema vertification. I amm looking at mongokit, but I want something which is similar to mappers, so that it would save from the object's property, and not a dict. i would like a mapper so that i can use existing objects without modifying ...
Another option is MongoEngine. The ORM for MongoEngine is very similar to the ORM used by Django. Example (from the tutorial): class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User) class TextPost(Post): content = StringField() class ImagePost(Post): ima...
MongoDB
2,781,682
96
I'm used to using relational databases like MySQL or PostgreSQL, and combined with MVC frameworks such as Symfony, RoR or Django, and I think it works great. But lately I've heard a lot about MongoDB which is a non-relational database, or, to quote the official definition, a scalable, high-performance, open source, ...
Here are some of the advantages of MongoDB for building web applications: A document-based data model. The basic unit of storage is analogous to JSON, Python dictionaries, Ruby hashes, etc. This is a rich data structure capable of holding arrays and other documents. This means you can often represent in a single entit...
MongoDB
2,117,372
96
I am using mongoose findOneAndUpdate but still getting the error, DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead. But I am not even using findAndModify, why is it converting my query to findAndModify?
You need to set the option in the query useFindAndModify to false, as mentioned in the docs. (search keyword Currently supported options are) 'useFindAndModify': true by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify(). and if you se...
MongoDB
52,572,852
95
So as you all know, find() returns an array of results, with findOne() returning just a simply object. With Angular, this makes a huge difference. Instead of going {{myresult[0].name}}, I can simply just write {{myresult.name}}. I have found that the $lookup method in the aggregate pipeline returns an array of results ...
You're almost there, you need to add another $project stage to your pipeline and use the $arrayElemAt to return the single element in the array. db.users.aggregate( [ { "$project": { "fullName": { "$concat": [ "$firstName", " ", "$lastName"] }, ...
MongoDB
37,691,727
95
Let's say I insert the document. post = { some dictionary } mongo_id = mycollection.insert(post) Now, let's say I want to add a field and update it. How do I do that? This doesn't seem to work..... post = mycollection.find_one({"_id":mongo_id}) post['newfield'] = "abc" mycollection.save(post)
In pymongo you can update with: mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False) Upsert parameter will insert instead of updating if the post is not found in the database. Documentation is available at mongodb site. UPDATE For version > 3 use update_one instead of update: mycollection.update_one({'_...
MongoDB
4,372,797
95
I have a mongoDB collection with millions of rows and I'm trying to optimize my queries. I'm currently using the aggregation framework to retrieve data and group them as I want. My typical aggregation query is something like : $match > $group > $ group > $project However, I noticed that the last parts only take a few m...
The main purpose of the aggregation framework is to ease the query of a big number of entries and generate a low number of results that hold value to you. As you have said, you can also use multiple find queries, but remember that you can not create new fields with find queries. On the other hand, the $group stage allo...
MongoDB
28,364,319
94
I have this data in mongodb: { "name": "Amey", "country": "India", "region": "Dhule,Maharashtra" } and I want to retrieve the data while passing a field name as a variable in query. Following does not work: var name = req.params.name; var value = req.params.value; collection.findOne({name: value}, functi...
You need to set the key of the query object dynamically: var name = req.params.name; var value = req.params.value; var query = {}; query[name] = value; collection.findOne(query, function (err, item) { ... }); When you do {name: value}, the key is the string 'name' and not the value of the variable name.
MongoDB
17,039,018
94
I was trying to run MongoDB: E:\mongo\bin>mongod mongod --help for help and startup options Sun Nov 06 18:48:37 Sun Nov 06 18:48:37 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability. Sun Nov 06 18:48:37 Sun Nov 06 18:48:37 [initandlisten...
After installing the MongoDB you should manually create a data folder. By default MongoDB will store data in /data/db, but it won't automatically create that directory. To create it, do: $ sudo mkdir -p /data/db/ $ sudo chown `id -u` /data/db You can also tell MongoDB to use a different data directory, with the --d...
MongoDB
8,029,064
94
I'm starting a hobby (non-revenue) project using Ruby on Rails. I've done a fair amount of development in Rails using Postgresql, and I can make a pretty good imitation of normalized schema. However, Mongrodb looks shiny and new. What better for trying out something new than a hobby project? Think back to when you s...
I would definitely second the recommendation of MongoMapper if you're going to be using MongoDB with Rails. I will warn you, however, that there is (so far) no documentation other than a couple blog posts. If you're not comfortable digging into the source code to see how things work, it's probably not for you yet. If y...
MongoDB
2,124,274
94
I'm working on a query to find cities with most zips for each state: db.zips.distinct("state", db.zips.aggregate([ { $group: { _id: { state: "$state", city: "$city" }, numberOfzipcodes: { $sum: 1 } } }, { $sort: { numberOfzi...
You can use $addToSet with the aggregation framework to count distinct objects. For example: db.collectionName.aggregate([{ $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}} }]) Or extended to get your unique values into a proper list rather than a sub-document inside a null _id record: db.collectionNam...
MongoDB
16,368,638
93
I have a process that returns a list of String MongoDB ids, [512d5793abb900bf3e20d012, 512d5793abb900bf3e20d011] And I want to fire a single query to Mongo and get the matching documents back in the same order as the list. What is the shell notation to do this?
After converting the strings into ObjectIds, you can use the $in operator to get the docs in the list. There isn't any query notation to get the docs back in the order of your list, but see here for some ways to handle that. var ids = ['512d5793abb900bf3e20d012', '512d5793abb900bf3e20d011']; var obj_ids = ids.map(funct...
MongoDB
15,102,532
93
Replication seems to be a lot simpler than sharding, unless I am missing the benefits of what sharding is actually trying to achieve. Don't they both provide horizontal scaling?
In the context of scaling MongoDB: replication creates additional copies of the data and allows for automatic failover to another node. Replication may help with horizontal scaling of reads if you are OK to read data that potentially isn't the latest. sharding allows for horizontal scaling of data writes by partition...
MongoDB
11,571,273
93
Is there a super UNIX like "root" user for MongoDB? I've been looking at http://docs.mongodb.org/manual/reference/user-privileges/ and have tried many combinations, but they all seem to lack in an area or another. Surely there is a role that is above all the ones listed there.
The best superuser role would be the root.The Syntax is: use admin db.createUser( { user: "root", pwd: "password", roles: [ "root" ] }) For more details look at built-in roles.
MongoDB
20,117,104
92
How would I mock out the database in my node.js application, which in this case uses mongodb as the backend for a blog REST API ? Sure, I could set the database to a specific testing -database, but I would still save data and not test my code only, but also the database, so I am actually not doing unit testing but inte...
I don't think database related code can be properly tested without testing it with the database software. That's because the code you're testing is not just javascript but also the database query string. Even though in your case the queries look simple you can't rely on it being that way forever. So any database emulat...
MongoDB
12,526,160
92
We all know that Meteor offers the miniMongo driver which seamlessly allows the client to access the persistent layer (MongoDB). If any client can access the persistent API how does one secure his application? What are the security mechanisms that Meteor provides and in what context should they be used?
When you create a app using meteor command, by default the app includes the following packages: AUTOPUBLISH INSECURE Together, these mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools (development purposes only), but typically not appropriate ...
MongoDB
10,099,843
92
I am working with new official mongodb driver for golang. I have created one complex query to insert the data into mongo db and then sort it according to an element value. I am using a filter in which I have created the bson type using :- filter := bson.D{{"autorefid", "100"}} But It is showing a warning saying: prim...
The warnings can be stopped by setting the check flag to false. $ go doc cmd/vet By default all checks are performed. If any flags are explicitly set to true, only those tests are run. Conversely, if any flag is explicitly set to false, only those tests are disabled. Thus -printf=true runs the printf check, -prin...
MongoDB
54,548,441
91
I'm new in nodeJS, started learning by following a trailer on youtube, everything goes well until I added the connect function if mongodb, mongo.connect("mongodb://localhost:27017/mydb") when I run my code on cmd (node start-app), get the following error, MongoNetworkError: failed to connect to server [localhost:2701...
You have to install MongoDB database server first in your system and start it. Use the below link to install MongoDB https://docs.mongodb.com/manual/installation/ If you have installed MongoDB check if the server is in which state (start/stop). Try to connect through mongo shell client.
MongoDB
50,173,080
91
I'm trying to develop a class on the top of the mongoose with my custom methods, so I extended the mongoose with my own class but when I invoke to create a new car method it works but its strip and error, here I let you see what I'm trying to do. I'm getting this warning (node:3341) DeprecationWarning: Mongoose: mpromi...
Here's what worked for me to clear up the issue, after reading docs: http://mongoosejs.com/docs/promises.html The example in the doc is using the bluebird promise library but I chose to go with native ES6 promises. In the file where I'm calling mongoose.connect: mongoose.Promise = global.Promise; mongoose.connect('mong...
MongoDB
38,138,445
91
How do I truncate a collection in MongoDB or is there such a thing? Right now I have to delete 6 large collections all at once and I'm stopping the server, deleting the database files and then recreating the database and the collections in it. Is there a way to delete the data and leave the collection as it is? The del...
To truncate a collection and keep the indexes use db.<collection>.remove({})
MongoDB
16,493,902
91
Simple question, do arrays keep their order when stored in MongoDB?
yep MongoDB keeps the order of the array.. just like Javascript engines..
MongoDB
9,013,916
91
I am running a web server on node the code for which is given below var restify = require('restify'); var server = restify.createServer(); var quotes = [ { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"}, { author : 'Walt Disney', text : "You may not realize it whe...
getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without http: var optionsget = { host : 'localhost', port : 3010, path : '/quote/random', // the rest of the url with parameters if needed method : 'GET' // do GET }; Regarding learning resources, yo...
MongoDB
23,259,697
90
For some collection with a field { wins: Number }, how could I use MongoDB Aggregation Framework to get the total number of wins across all documents in a collection? Example: If I have 3 documents with wins: 5, wins: 8, wins: 12 respectively, how could I use MongoDB Aggregation Framework to return the total number, i....
Sum To get the sum of a grouped field when using the Aggregation Framework of MongoDB, you'll need to use $group and $sum: db.characters.aggregate([ { $group: { _id: null, total: { $sum: "$wins" } } } ] ) In this case, if you want to get the sum of all of the wins, yo...
MongoDB
17,044,587
90
Is there a way to store Enums as string names rather than ordinal values? Example: Imagine I've got this enum: public enum Gender { Female, Male } Now if some imaginary User exists with ... Gender gender = Gender.Male; ... it'll be stored in MongoDb database as { ... "Gender" : 1 ... } but i'd prefer somethin...
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class Person { [JsonConverter(typeof(StringEnumConverter))] // JSON.Net [BsonRepresentation(BsonType.String)] // Mongo public Gender Gender { get; set; } }
MongoDB
6,996,399
90
I have a problem where I want to be able to get all the unique cities for a collection, and my code looks something like this: var mongoose = require("mongoose"), Schema = mongoose.Schema; var PersonSchema = new Schema({ name: String, born_in_city: String }); var Person = mongoose.model('Person', PersonSchema)...
Just to give an update for Mongoose 3.x: MyModel.find().distinct('_id', function(error, ids) { // ids is an array of all ObjectIds });
MongoDB
6,043,847
90