FAQ Database Discussion Community


Creating index while updating the documents

mongodb,indexing
I have a collection I am updating adding a new field. The document looks like: {"A": "P145", "B":"adf", "C":[{"df":"14", "color":"blue"},{"df":17}], "_id":ObjectID(....), "Synonyms":{"Synonym1": "value1", "Synonym2": ["value1", "value2"]}} In the update I am adding new elements to C I want to create a index on the field A and B. A and...

How could I get the matched nested items in array

mongodb
How could I get the matched nested items in array I want to return the matched items in nested array. For example, I want to filter out the records that contain "A428 ","A429 " in their items How could I get it ? Query pipeline_work = [ { '$match': 'records.items':...

Solved: Trouble updating a document that has both belongs_to and has_many associations

ruby-on-rails,mongodb,mongoid,nomethoderror
I'm having trouble with my Rails/Mongoid app whenever I'm updating my documents. I'm at my wits' ends and I could use some help. I have three collections: owners, vessels and modifications. class Owner include Mongoid::Document has_many :vessels field :name, type: String field :uprn, type: String end class Vessel include Mongoid::Document...

how to update array of object in mongodb with for loop

javascript,node.js,mongodb
i want to update nested mongo document with for loop here is my node.js code; //loop starts var update = { "rate":mainRate, "classifierCategories."+e+".rate":temiz[i].slice(0,2) }; classifier.update({"classifierShortName":arrFile[1]},update,function(err){ console.log("updated - "+i+" - "+e); }); //loop end Error accurs ; Unexpected token + How can i update classifierCategories array with for loop...

Conditionally group and sum of the elements from an array

java,mongodb,mongodb-query,mangodb
I want to group by APPName and I want find how many PrestoBarImpression, PrestoKeyCountChange, PrestoTileImpression for every application for a particular day (just the sum of order counts). This is so I can generate a report with this information. I need how many order counts of PrestoTileImpression, how many order...

Exclude _id field in mongodb while inserting

mongodb
Is there any possibilities of without having _id field in mongodb collection?? I don't want it because i need to load mongodb data into apache pig, which will not support _id. So, i just don't want _id field in my mongodb collections. Anyone please help.. Thanks in advance....

MongoDB, How to query subdocuments close to specific location?

node.js,mongodb,geojson
I have MongoDb database with collection users containing documents structured as below: { firstName: "firstname", "phone": "123456", "places":[ { "name" : "somename", "address" : "Woollahra, New South Wales, Australia", "loc" : { "type" : "Point", "coordinates" : [ 151.23721839999996, -33.8884085 ] }, "url" : "ttttt2", "registeredOn" : ISODate("2015-06-17T20:14:10.986Z"), "id" :...

mongodb populate method not working

node.js,mongodb,model,populate,auto-populate
Here is my code for models var postSchema = new mongoose.Schema({ created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true }, //should be changed to ObjectId, ref "User" created_at: {type: Date, default: Date.now}, text: String }); var userSchema = new mongoose.Schema({ username: String, password: String, //hash created from password created_at: {type: Date, default:...

How to add a subdocument in a mongoose schema

javascript,node.js,mongodb,mongoose
I am trying to create a subdocument in a mongoose schema from node.js/Express. I have two schemas: Member and Address Member.js // app/models/member.js // load mongoose since we need it to define a model var mongoose = require('mongoose'), Schema = mongoose.Schema var Address = require('./address'); var MemberSchema = Schema({ FName...

Projection with single child object

mongodb,projection
Say I have something like: { "_id" : 1, "semester" : 1, "grades" : { student1: 70, student2: 85 }} { "_id" : 1, "semester" : 1, "grades" : { student1: 55, student2: 24 }} I want to do a find() and in my projection I just want student2, which...

Query not working - MongoDB

mongodb
Given this kind of documents: "_id" : ObjectId("5461c8f0426f727f16010000"), "f" : [ { "t" : "ry", "v" : 1972 }, { "t" : "g", "v" : [ "Crime", "Drama" ] }, { "t" : "ml", "v" : "English" }, { "t" : "k", "v" : "movie" }, { "t" : "ai",...

Mongo Collection Find By Id with Filter

c#,mongodb,mongodb-query
To find one item from mongo collection, I am trying to apply filter and to the collection. But there is a compilation error as below. This code is taken from official mongodb docs var filter = Builders<BsonDocument>.Filter.Eq("_id", id); var result = _collection.Find(filter); ...

How to check if multiple documents exist

mongodb,mongodb-query
Is there such a query that gets multiple fields, and returns which of these exists in the collection? For example, if the collection has only: {id : 1} {id : 2} And I want to know which of [{id : 1} , {id : 3}] exists in it, then the...

Query an array of embedded documents in mongodb

mongodb,embedded-documents
I'm having a little trouble writing a query that needs to compare a given value against a certain field in all embedded documents within an array. I will give an example to make the issue less abstract. Let's say I want to use MongoDB to store the last queries that...

Node.js app giving ERR_EMPTY_RESPONSE

javascript,node.js,mongodb,npm
I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the...

Download of GridFs using nodejs does not start

node.js,mongodb,gridfs,gridfs-stream
I'm trying to download a binary file of +200M saved in a mongoDB using the GridFS. My problem is that the download won't start. I'm using nodejs with mongodb and gridfs-stream. In routes.js: router.get('/getlog',function(req,res) { if (req.isAuthenticated()) { var mongo = require('mongodb'); var Grid = require('gridfs-stream'); var db = new...

What does "new BsonValue[]{x,y,z} do?

mongodb,mongodb-csharp
This code is used with the C# driver to select items from a document of items that have a location field value in the range of location id values, I am just providing it as an example: var locations = new BsonValue[] { 1, 2, 3, 4 }; var data...

DB relationship: implementing a conversation

mongodb,meteor
I want to implement a simple conversation feature, where each conversation has a set of messages between two users. My question is, if I have a reference from a message to a conversation, whether I should have a reference the other way as well. Right now, each message has conversationId....

Can angularjs connect directly to mongodb?

angularjs,mongodb
I am new to angularjs and as the title said, I am wondering if there is a way to connect angularjs directly to mongodb without coding additional server side using express.js. i tried to search on the Internet but i cannot find any resources.

Morphia - How to replace LongIdEntity.StoredId in last version?

java,mongodb,morphia
I just switched to the last version of Morphia (1.0.1). The previous one was com.github.jmkgreen.morphia 1.2.3. I don't know how to replace LongIdEntity.StoredId. I use it to increment a long id. edit : Here is how it worked before: public Key<Snapshot> save(PTSnapshot entity) { if (entity.getId() == null) { String...

How to correctly update embedded object's field in mongodb?

mongodb
How do i correctly update the resetPasswordExpires field in mongodb document: { "_id" : ObjectId("000"), "username" : "root", "isActive" : "yes", "email" : "[email protected]", "roles" : { "admin" : ObjectId("111") }, "resetPasswordExpires" : ISODate("2015-06-19T18:04:40.014Z"), "resetPasswordToken" : "token" } I tried: db.users.update( { item: "000" }, { $set: { "roles.resetPasswordExpires": ISODate("2015-06-20T18:04:40.014Z")}...

Live Preview Iframe

javascript,node.js,mongodb,iframe
I am building a site in node.js that allows users to have a custom page that can be edited in a dashboard. I would like this dashboard to have a live preview (similar to the way Shopify does it) in an iframe, where every time the user makes changes, the...

Creating unique Mongoose objects from CSV

javascript,node.js,mongodb,csv,mongoose
Let's say that I have a CSV containing information that needs to be parsed into different Mongoose objects. I need to either find or create a "User" based on a some information in the CSV file. If I run this, however, it will create a new User each time, since...

MongoDb c# bad unknown operator exception

c#,mongodb,mongodb-csharp
I execute the following query : { $query : { "userId" : 11851, "p2l.listId" : 38882, "isDeleted" : false }, $orderby: { email: 1}, $skip: 0, $limit:100 } via the following code : BsonDocument document = BsonSerializer.Deserialize<BsonDocument>(queryString); QueryDocument queryDoc = new QueryDocument(document); var toReturn = collection.Find(queryDoc); return toReturn.ToList(); and I...

What are some patterns I can look at for database implementations in JavaScript?

javascript,node.js,mongodb
I'm fairly new to JavaScript, and I'm busy playing around with a node test app and MongoDB. I'm at a point where I'd like to start with the db side of the app, but I'm not sure what patterns are most commonly used in such a stack, and more importantly,...

Convert string to ISODate in MongoDB

javascript,python,mongodb,date
I am new to MongoDB and I am stuck on the String to Date conversion. In the db the date item is stored in String type as "date":"2015-06-16T17:50:30.081Z" I want to group the docs by date and calculate the sum of each day so I have to extract year, month...

Converting an html page to binary format in python

python,html,mongodb,binary
Suppose I have these two lines: c=urllib2.urlopen(myUrl) html=c.read() I'm quite new to Python and am looking for a way to transform the HTML code stored in html in a binary array so I could easily store in my MongoDB without worrying about the encoding of the webpage I downloaded. Suggestions?...

Use JSON file to insert data in database

javascript,json,mongodb,meteor,data
I'm using my JSON file like this to insert data in my collection : var content = JSON.parse(Assets.getText('test.json')); console.log('inserting...'); Profiles.insert({ user: id, data:content }; But I would like to have a "data's tree" like that : [ user: "rtegert23423131", firstname:"test", surname:"test2", // ... ] Not like that : [ user:...

ObjectID not storing hexadecimal value

javascript,node.js,mongodb,sails.js,waterline
Originally, my Sails/Mongo was storing the ObjectID in the database as follows: "_id" : ObjectId("557077fb836bdee256004232") Not sure what changed or happened, but now new records are being stored as follows: "_id" : { "_bsontype" : "ObjectID", "id" : "UtÓ-Åß\u0010C&5", "generationTime" : 1434552692 } This is only occurring in 2 developer...

Mongoose : update collection with previous data

node.js,mongodb,mongoose
I am learning NodeJs and for a demo project i need to use MonGoDB with Mongoose. I created a collection for a photo album. The first row is : albumName and the second row is : pictures. I don't undersand how i can save all my pictures in the row...

Meteor/MongoDB limiting the result

mongodb,meteor
I am trying to find all documents and publish at most 5 from the results. Following this section of the MongoDB doc, I am trying to do this: Meteor.publish('teams', function () { return Teams.find().limit(5); }); Yet, in the server console, I get an exception: Exception from sub teams id Pm6jKL8Sv3FSDSTfM...

Why the query scans 8x times the documents it finds - MongoDB

mongodb
I've got 50 documents (for trial purposes) more or less like this one: "_id" : ObjectId("5461c8f0426f727f16010000"), "f" : [ { "t" : "ry", "v" : 1972 }, { "t" : "g", "v" : [ "Crime", "Drama" ] }, { "t" : "ml", "v" : "English" }, { "t" : "k",...

Is it possible to perform two commands in the console MongoDB

mongodb
Good afternoon You can run two commands, one line in the console MongoDB? for example: db.getMongo().setSlaveOk(); show dbs but it does not work...

Are the changes done by db command in MongoDB permanent and how?

mongodb,mongodb-query
Are the changes done using the shell in mongodb permanent ? And how MongoDb detects the config file? I am stuck in setting Slow query logs in MongoDb. We have a command db.setProfilingLevel() to set profiling level. But how can we set profiling for all databases and how to set...

Order records by mapping collections

mongodb,mongodb-query
I have 2 collections as follows Author: {id:'1',name:'JK', bookCount:3} {id:'2',name:'SS', bookCount:2} {id:'3',name:'CC', bookCount:4} Book: ( authorId : foreign key to Author collections) {name:'Book 1',authorId:1} {name:'Book 2',authorId:1} {name:'Book 3',authorId:1} {name:'Book 4',authorId:2} {name:'Book 5',authorId:2} {name:'Book 6',authorId:3} {name:'Book 7',authorId:3} {name:'Book 8',authorId:3} {name:'Book 9',authorId:3} I want to write a mongo query, which gives books,ordered...

Update all properties of object in MongoDb

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I'm using the MongoDB .Net driver in my project. I want to update all of the properties of my object that is stored in MongoDB. In the documentation, update is shown like this: var filter = Builders<BsonDocument>.Filter.Eq("i", 10); var update = Builders<BsonDocument>.Update.Set("i", 110); await collection.UpdateOneAsync(filter, update); But I don't want...

MongoJS - No Error On Unique Index

mongodb,mongojs
So I'm messing around with MongoDB using MongoJS and can't seem to get an error to be returned when a unique ID exists. So this is the code I am using: server.post('/register', function (req, res, next) { var details = req.params; details.password = md5(details.password).toString(); db.users.insert(details, function (err, test1, test2) {...

Incorrect response to mapReduce query in mongo-db

mongodb,mapreduce
I have 1000 user records in collecton, in which 459 document has gender male and remaining as female //document structure > db.user_details.find().pretty() { "_id" : ObjectId("557e610d626754910f0974a4"), "id" : 0, "name" : "Leanne Flinn", "email" : "[email protected]", "work" : "Unilogic", "dob" : "Fri Jun 11 1965 20:50:58 GMT+0530 (IST)", "age" :...

Data not visible in mongoDB when inserted from PyMongo

python,mongodb,pymongo
I am trying to insert data in a mongodb collection from python but the data is not being logged. This is how I am doing it: from pymongo import MongoClient import time class data2db: def __init__(self): pass def enter_data(self,data): client = MongoClient('127.0.0.1', 27017) db = client.db coll=db.Temperature1 post = {"auth":...

how give different privilege for user and admin in mongodb

javascript,mongodb,mongoose,sails.js
I'm creating the an application using sails and MongoDB. where I need three level of user. Super admin admin user I want to give the different privileges for each of user Super admin can access whole DB. Admin can access the data relate to that field User can access the...

add subitems to meteor document

mongodb,meteor,collections,insert-update
I have a meteor collection "list" that has the following data structure. "list" : [ { "_id" : "id", "author" : "authorId", "createdOn" : "DateTime", "description" : "description", "items" : [ { "item1" : { "itemComplete" : "Boolean", "itemName" : "item name", "itemDescription" : "item description", } }, { "item2"...

Mysql InnoDB vs Mongodb write performance

mysql,mongodb
I need to increment a counter each time a web page is rendered. When I use mongodb to do that, I can do about 16000 writes per second on a 4 cores/8 threads CPU on a regular disk. When I use Mysql InnoDB table, I can do only... 30 writes...

c# mongodb driver groupby

c#,mongodb,mongodb-csharp
I try to execute this query: MongoCollection<AnalyticsClicks> dbCollection = DetermineCollectionName<AnalyticsClicks>(); var query = from c in dbCollection.AsQueryable() where c.UserId == userId && c.CampaignId == campaignId select new { c.Email, c.Link }; var res = query.GroupBy(x => x.Email, b => b.Link).Count(); but I have exception: The GroupBy query operator is not...

How to defer reading until writing is done?

javascript,node.js,mongodb,websocket,socket.io
I'm making a multiplayer game using node.js, socket.io and MongoDB. When a player die they can reload the browser just before the fatal hit and still be alive even though the kill was registered. I'm using the following solution to save/load a player: socket.sockets.on('connection', onSocketConnection); function onSocketConnection(client) { util.log('New player...

Is it possible to insert(not update) a field name as variable in Mongodb?

javascript,mongodb,meteor
Im trying to insert a embedded document in mongodb for a meteor project. 'submit form' : function(event){ event.preventDefault(); var query=document.getElementsByClassName("twilioProcessorsms")[0].value; ChoiceList.insert({ sms: esms, query: { accountSID: accsid, authToken: token, phoneNumber: phno} }); I am trying to have the "query" as a variable. But it considers query as a string.I dont...

Is there a built-in function to get all unique values in an array field, across all records?

arrays,node.js,mongodb,mongoose,schema
My schema looks like this: var ArticleSchema = new Schema({ ... category: [{ type: String, default: ['general'] }], ... }); I want to parse through all records and find all unique values for this field across all records. This will be sent to the front-end via being called by service...

Getting failed to load c++ bson extension error using Mongodb and Node.js

javascript,node.js,mongodb
I am getting the following error while trying to run server using Node.ja with Mongodb. Error: { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++...

How to update and read a collection in MongoDB using Mongoose

javascript,node.js,mongodb,mongoose
I am having trouble with a project I am working on. I want to create a database in which I can store dates and links to YouTube videos in a MongoDB database. I am using Mongoose as the ORM. The problem seems to be that the database and collection is...

Does Mgo cache connection strings?

mongodb,go,mgo,compose
My Go application has been connecting to a MongoDB (hosted on Compose.io) using MGO with no issues. Today I decided to delete this database and add a different one (again using Compose). I updated the connection string. So I connect using: db, err := mgo.Dial("mongodb://<username>:<password>@dogen.mongohq.com:10048/db-name") with the username and password...

Unclean shutdown with MongoDB results in corrupted mongod.lock file

node.js,mongodb
I have a MongoDB database storing data in a particular directory, and I am using a Node.js process to write to it. Sometimes my Node.js process experiences a forced shutdown (notice the passive voice) and I get this error message, which pretty much means I have to go in and...

Use $or operator in @Query annotation in spring data mongodb repository

java,spring,mongodb,spring-data-mongodb
I am using spring-data-mongodb. I want to use $or operator in my repository. This is my query: @Query("{'type':?0}") List<Doc> findByType(String type, Pageable pageable); How do use $or in @Query so as it can match either type or name and fetch me a document. Please help....

Get matching elements in mongodb array

php,mongodb,aggregation,pipeline
I want to use aggregation to get this array only with those tickets, which have start field after 2015-06-16. Can someone help me with the pipeline? { "name" : "array", "tickets" : [ { "id" : 1, "sort" : true, "start" : ISODate("2015-06-15T22:00:00.000Z") }, { "id" : 2, "sort" :...

How to remove duplicate values inside a list in mongodb

mongodb,mongodb-query,pymongo,aggregation-framework
I have a mongodb collection . When I do. db.bill.find({}) I get, { "_id" : ObjectId("55695ea145e8a960bef8b87a"), "name" : "ABC. Net", "code" : "1-98tfv", "abbreviation" : "ABC", "bill_codes" : [ 190215, 44124, 190215, 147708 ], "customer_name" : "abc" } I need an operation to remove the duplicate values from the bill_codes....

Handling Custom BSON Marshaling (Golang & mgo)

json,mongodb,go,bson
I have a number of structs that require custom marshalling. When I was testing I was using JSON and the standard JSON marshaller. As it doesn't marshal unexported fields, I needed to write a custom MarshalJSON function, which worked perfectly. When I called json.Marshal on the parent struct containing the...

How to get node.js to connect to mongolab using mongoose

database,node.js,mongodb,mongoose,mongolab
I've been trying to use mongoose (module for node.js and mongodb). And tried to get a connection with mongolab up and running. I tried the following at the top of my app.js file, but I couldn't seem to enter the db.on function. global.mongoose = require('mongoose'); var uri = 'mongodb://username:password#####@ds.mongolab.com:#####/db'; global.db...

Returning a subset of array items in MongoDB

arrays,node.js,mongodb
Can anyone offer advice on how I would return a subset of array items? For example, let's suppose I have a collection of documents (similar to the example below) that contains a simple _id key and a key that contains an array of objects. I would like to find all...

Find Mongoid geospacial circles that contain a point

mongodb,mongoid,geospatial
I have Mongoid documents that represent services offered by local merchants. Each has one or more locations (lat/lng point) with a service area (radius). Given a customer location (lat/lng point), how can I find all the documents where the customer location falls within the service area? class Service include Mongoid::Document...

Mongoose population in instance methods

node.js,mongodb,mongoose,mongoose-populate
I have a model with reference to other documents. I would like to have a method in that model that can process data used in the referenced models. 'use strict'; var mongoose = require('mongoose') , Schema = mongoose.Schema , deepPopulate = require('mongoose-deep-populate'); var MainSchema = new Schema({ childs: [{type:Schema.ObjectId, ref:...

MongoDB. Index was out of range

c#,mongodb,mongodb-csharp
I keep having this error as I try to retrieve thousands of documents from the collection. index was out of range. must be non-negative and less than the size of the collection. parameter : Index Here is my code as I query the documents: MongoCollection<Book> collection = PDatabase.GetCollection<Book>("books"); List<IProduct> products...

Compare Array with Collection-Array containing Objects

node.js,mongodb,mongoose,schema
This is my collection schema: var objectSchema = new Schema({ members: [{ user_id: ObjectId, settings: { type: Boolean } }], title: String }); And now I'm trying to search for objects with specific members (identified by their "user_id", for example ["asdf123lkd", "asdf1223"]). Is there any way to search for these...

How update the first element of an array in mongoDB?

node.js,mongodb,mongoose
I am learning NodeJs and MongoDb and I will create a photo album. I encounter a problem with mongoDB. In fact, after uploading a picture, I push new pictures into the database like this : AlbumPicture.update({album:'album1'}, {$push: {pictures:file_name}}, function(err, data){ if(err){ console.log(err); } console.log('Database Updated'); }); The problem is :...

Why does mongoose model's hasOwnProperty return false when property does exist?

node.js,mongodb,mongoose,passport.js
I have this code : user.findOne( { 'email' : email }, function( err, User ) { if ( err ) { return done(err); } if ( !User ) { return done(null, false, { error : "User not found"}); } if ( !User.hasOwnProperty('local') || !User.local.hasOwnProperty('password') ) { console.log("here: " + User.hasOwnProperty('local'));...

mongoexport fields from subdocuments to csv

mongodb
I am trying to export a field from a subdocument with no luck. Here is my syntax; mongoexport -d test -c accounts -f account_number,situses.coordinates -o coordinates.csv --type=csv The output includes the account_number but not the coordinates field from the subdocument. According to the docs, this is supposed to work. The...

Meteor - Query Embedded Documents

javascript,mongodb,meteor
I would like to fetch only specific fields in embedded documents of my collection. One Document of my Collection: "_id" : "fDa9J245hkKnZyipM", "OrderID" : "qPypJCWov79dQ2nc2", "MWLink" : { "LinkType" : "KRF - PPUI - LOO", "LinkID" : "test3", "SiteA" : "placeA", "SiteB" : "placeB" } My helper: linkID: function() {...

Do you get the same performance using index prefixes?

performance,mongodb,indexing
Say I have a collection containing documents like the one below: { _id: ObjectId(), myValue: 123, otherValue: 456 } I then create like below: {myValue: 1, otherValue: 1} If I execute the following query: db.myCollection.find({myValue: 123}) will I get the same performance with my index as I would if I...

Working with embedded documents in MongoDB

javascript,mongodb,meteor
I have a document with the following structure, some fields omitted for brevity; { _id: 1, projectName: name, managers: [ { managerId: manager1, status: false, startDate: startDate, endDate: endDate }, { managerId: manager2, status: false, startDate: startDate, endDate: endDate } { managerId: manager3, status: true, startDate: startDate, endDate: endDate }...

mongodb aggregate unwind array and no array

arrays,mongodb,aggregation-framework
I'm trying to write an aggregate query using $unwind no matter the element is an array or not. I know $unwind does not work on no array elements, but I wonder if there is a way to make it work, like converting this element into an array. I have a...

google maps refresh without displaying gray

javascript,jquery,mongodb,google-maps,google-maps-api-3
I am using the Google Maps API v3 in javascript, and I am constantly reloading the map with an app.get, and adding layers and bookmarks using mongodb. To erase everything I reload the map, and while it's loading a gray background displays in the div that contains the map. What...

mongodb bind ip won't work unless set to 0.0.0.0

mongodb
I really tried, even reinstall the mongodb. And it's the same to MongoDB bind_ip error: bind() failed errno:99 Cannot assign requested address for socket It works if set bind_ip to: 0.0.0.0, or 127.0.0.1 $ sudo service mongod start mongod start/running, process 30040 $ sudo service mongod restart mongod stop/waiting mongod...

How to query a Document by ObjectId with rmongodb

r,mongodb,rmongodb
Here is what you get in mongo shell : db.col.find(ObjectId("5571849db1969e0a6eb32731")).pretty() { "_id" : ObjectId("5571849db1969e0a6eb32731"), "name" : "Some name", "logo" : "Some logo", "users" : [ ObjectId("5571830031c7fc341bc2e105"), ObjectId("5571830031c7fc341bc2e107") ], "admins" : [ ], "__v" : 0, "steps" : 5782 } Here is what I get in rmongo : myResult <- mongo.find(Connexion,...

mongoose won't update object field

mongodb
I am new to moogoose, i am running into the difficult to update object in the db. here is my shcema. var FormSchema = new Schema({ formContent : { type : Object, required : true }, formName : String, createdDateTime : Date }); Here is the controller to update the...

Does MongoDB find() query return documents sorted by creation time?

database,mongodb,sorting
I need documents sorted by creation time (from oldest to newest). Since ObjectID saves timestamp by default, we can use it to get documents sorted by creation time with CollectionName.find().sort({_id: 1}). Also, I noticed that regular CollectionName.find() query always returns the documents in same order as CollectionName.find().sort({_id: 1}). My question...

Mongodb query documents where nested array is equal or subset of fixed array

c#,arrays,mongodb,subset,mongodb-csharp
I keep banging my head against the wall trying to solve the following problem (I'm using the new c# 2.0 driver): The idea is to return all docs where the nested array is equal or a subset of a fixed array. Example: Fixed array: [ "A", "B", "C" ] container...

Query with filter builder on nested array using MongoDB C# driver

c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0
Consider the following object structure stored as documents: public class Foo { public string Id { get; set; } public ICollection<FooBar> Bars { get; set; } // ... } public class FooBar { public string BarId { get; set; } // ... } Using a LINQ-style query with the driver...

mongoDB query with case insensitive schema element

mongodb,nosql
In my MongoDB collection I have added a record as follows db.teacher.insert({_id:1 ,"name":"Kaushik"}) If I search db.teacher.find({name:"Kaushik"}) I get one record. But if I try "NAME" instead of "name" i.e. db.teacher.find({NAME:"Kaushik"}) It won't return any record. It means that I must know how schema element is spelled exactly with exact...

BsonClassMap Serializer' is not configurable using an attribute of type 'BsonRepresentation Attribute'

c#,mongodb,nosql,document,bson
I am a beginner in mongodb. I have a hierarchial models in mongo, Please see my code below. public class Technology { public Technology() { ProductGroups = new List<ProductGroup>().ToArray(); } [BsonRepresentation(BsonType.ObjectId)] public ObjectId _id { get; set; } public string Name { get; set; } [BsonRepresentation(BsonType.Array)] public ProductGroup[] ProductGroups {...

How to add new items to an array in MongoDB

arrays,node.js,mongodb
I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that...

MongoDB: find documents with a given array of subdocuments

arrays,mongodb,find,aggregate,subdocument
I want to find documents which contain given subdocuments, let's say I have the following documents in my commits collection: // Document 1 { "commit": 1, "authors" : [ {"name" : "Joe", "lastname" : "Doe"}, {"name" : "Joe", "lastname" : "Doe"} ] } // Document 2 { "commit": 2, "authors"...

Mongoose findByID return no error when id not set [duplicate]

node.js,mongodb,mongoose
This question already has an answer here: node.js mongojs findOne callback returning error as null 1 answer I have a collection with an ID (_ID). { "_id": ObjectId("5583df9da55f654609901eed"), "group": "Tomorrowland", "description": "Délire 2015 à Tomorrowland", "uid": [ "5583df21a55f654609901eec", "5583e8ef9aeb31390bb50bf6" ], "pictures": [ "1434705960113.jpg", "1434705974710.jpg", "1434706147177.jpg", "1434711007201.jpg" ], "__v": 0...

paging subdocument in mongodb subdocument

mongodb,mongodb-query
I want to paging my data in Mongodb. I use slice operator but can not paging my data. I wish to bring my row but can not paging in this row. I want to return only 2 rows of data source. How can resolve it My Query : db.getCollection('forms').find({ "_id":...

How can i insert current date in robomongo?

java,mongodb,robomongo
I want to add a date field in mongo db. I am using robo mongo. How can i do that? If it is a string we can do it by "", if it is a number we can do it by NumberInt. What is the datatype for date field? Also,...

Async await usage for MongoDB repository

c#,mongodb,asynchronous,parallel-processing,async-await
I have a MongoDB repository class as you see below: public class MongoDbRepository<TEntity> : IRepository<TEntity> where TEntity : EntityBase { private IMongoClient client; private IMongoDatabase database; private IMongoCollection<TEntity> collection; public MongoDbRepository() { client = new MongoClient(); database = client.GetDatabase("Test"); collection = database.GetCollection<TEntity>(typeof(TEntity).Name); } public async Task Insert(TEntity entity) { if...

Get the MongoDB server version from node-mongodb-native in node.js

node.js,mongodb
This seems like a really easy thing and I wonder if this is my least clever question here on Stack Overflow. I would like to figure out the version of the MongoDB server that node-mongodb-native is connected to. However, I cannot seem to find anything regarding this using google. It's...

Mongoose installation failed on Mac

node.js,mongodb,mongoose
This was what I got in my terminal. I have mongoDB and node.js installed already.. If anyone can help me with this I'll appreciate it a lot! Thank you... ...

Cassandra data model to store embedded documents

mongodb,database-design,cassandra
In mongodb we can able to store embedded documents into a collection.Then, How do we store embedded documents into cassandra??? For this sample JSON representation??? UserProfile = { name: "user profile", Dave Jones: { email: {name: "email", value: "[email protected]", timestamp: 125555555}, userName: {name: "userName", value: "Dave", timestamp: 125555555} }, Paul...

mongodb shell is written in JavaScript. Why UNIX binary then?

javascript,mongodb,shell
Is that true, that MongoDB shell is written in JavaScript? If yes why it's a UNIX binary? Not a webapp for browser? > less /usr/local/bin/mongo "/usr/local/bin/mongo" may be a binary file. See it anyway? > file /usr/local/bin/mongo /usr/local/bin/mongo: Mach-O 64-bit executable x86_64 ...

MongoDB explain() cursor field

mongodb
I am starting to investigate into MongoDB and was looking into query stats and optimising through indexes. The examples I am reading use the explain function but their output is different from mine. Theirs looks like: { "cursor" : "BtreeCursor username_1", "nscanned" : 1, "nscannedObjects" : 1, "n" : 1,...

AngularJS factory dependencies

javascript,html,angularjs,mongodb
I'm using AngularJS to extract information stored in mongodb. I'm trying to use a factory to retrieve that information using $http . I read so much information about how to do it, and no one works for me. Also I'm using node + express, the routes works fine. The problem...

Mongotemplate - Query ObjectId according to greater than (gt) or less than (lt) operator

mongodb,spring-data,objectid
When I type this into my consol, it works: db.posts.find({"_id": {$lt:ObjectId("55732dccf58c555b6d3f1c5a")}}).limit(5).sort({"_id":-1}) When I use mongotemplate, it doesn't work and returns a blank array: @RequestMapping(value="/next", method=RequestMethod.GET) public List getNextPost(@RequestParam String next) { Query query = new Query(); query.addCriteria(Criteria.where("_id").lt("55732dccf58c555b6d3f1c5a")); List<Posts> posts = template.find(query, Posts.class); return posts; } I tried it with this...

push item in sub document

mongodb,mongodb-query
I have simple collection. I want to push item in question, but it gives an exception.How can I resolve it ? /* 1 */ my collection data { "_id" : ObjectId("557e8c93a6df1a22041e0879"), "QuestionCount" : 2.0000000000000000, "Questions" : [ { "_id" : ObjectId("557e8c9ba6df1a22041e087a"), "DataSource" : [], "DataSourceItemCount" : NumberLong(0) }, { "_id"...

How to overwrite object Id's in Mongo db while creating an App in Sails

mongodb,sails-mongo
I am new to Sails and Mongo Db. Currently I am trying to implement a CRUD Function using Sails where I want to save user details in Mongo db.In the model I have the following attributes "id":{ type:'Integer', min:100, autoincrement:true }, attributes: { name:{ type:'String', required:true, unique:true }, email_id:{ type:'EMAIL',...

Sorting a collection in doctrine2

php,mongodb,doctrine2,doctrine,odm
I've written the following query (that may or may not be efficient, I'm still a newbie): $collection = $this->dm->getConnection()->selectCollection('db_name', 'collection_name'); $query = array('array_name' => new \MongoId(id)); $cursor = $collection->find($query)->limit(9)->sort('r', 'desc'); I'm trying to sort by an r value that looks like this in the document: "r": 0.58325652219355106354 but it isn't...

Null set returned by mongodb aggregate Cursor in PHP

php,mongodb,mongodb-query,pymongo
MongoDB aggregate query returning empty set .Below is the query i am using in a php script to retrieve data from mongoDB .Please let me know where i am going wrong. $result = $collection->aggregateCursor([[ '$match'=> [ 'date'=> [ '$gte'=>ISODate("2015-06-01T00:00:00Z"), '$lte'=>ISODate("2015-06-03T00:00:00Z")] ] ],[ '$group'=> [ '_id'=> '$date', 'count'=> [ '$sum'=>1 ]...

using MongoDB aggregate count subdata

mongodb,aggregate
here is my data in mongodb: { "data": { "order_goods": [{ "category": 235 }, { "category": 666 }] } }, { "data": { order_goods: [{ "category": 235 }] } } here is my expected output: {"category":235, "total":2} {"category":666, "total":1} I have try many ways about aggregate such as $group, but...

Inserting a variable in MongoDB specifying _id field

python,mongodb,pymongo
I want to insert a variable, say, a = {1:2,3:4} into my database with a particular id "56". It is very clear from the docs that I can do the following: db.testcol.insert({"_id": "56", 1:2, 3:4}) However, I cannot figure out any way to insert "a" itself, specifying an id. In...

Why won't mgo unmarshall my struct properly?

mongodb,go,bson,mgo
Earlier I posted this question asking about writing custom BSON marshalling/unmarshalling in Go using mgo. Now I've come to test it I think I've hit on a bigger problem. All my structs unmarshal to nil values. This is my currency struct with the implementations of bson.Getter and bson.Setter: type Currency...

How to use a variable as an Object Key [MongoDB] [duplicate]

node.js,mongodb
This question already has an answer here: How to use a variable as a field name in mongodb-native findOne()? 1 answer I'm trying to use variable name given to me by my function, but its actually setting the object key equal to 'name' function addlist(name, item, id){ // Add...

Get json values from key-value pair without passing keys in meteor

javascript,json,mongodb,meteor
i am using keys to get the values from json in meteor. My json is in this format. { "_id" : "SXTJBs7QLXoyMFGpK", "Brand" : { "value" : "Nike" }, "Material" : { "value" : "Cooton" }, "Price" : { "value" : "67484" }, "ComboId" : { "value" : "y23" },...

Testing motor.MotorClient() connection

mongodb,tornado-motor
I want to know how to check that a Motor connection is successful. If i kill the mongod process and perform a: con = motor.MotorClient(host,port) I get "[W 150619 00:38:38 iostream:1126] Connect error on fd 11: ECONNREFUSED" Makes sense since there's no server running. However because this isn't an exception...

MongoDB Java Driver 3.0 MapReduce

mongodb,mongodb-java
This is the code I'm using to run map reduce on sourceCollectionName and to get the output to targetCollectionName. But the targetCollectionName is never created. new MongoClient("localhost").getDatabase(dbName).getCollection(sourceCollectionName) .mapReduce(map, reduce) .action(MapReduceAction.REPLACE) .databaseName(dbName) .collectionName(targetCollectionName) .sharded(false); Although I'm able to get output as MapReduceIterable and when I iterate this the result is dumped...