Menu
  • HOME
  • TAGS

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

java,mongodb,morphia

StoredId class is just a POJO with 3 fields: id className (to store the type of object the auto-increment will be done on, but you could store something lese, this is just used to retrieve the adequate increment value, because you could have more than one auto-incremented collection !) value...

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

node.js,mongodb,mongoose,passport.js

It's because the document object you get back from mongoose doesn't access the properties directly. It uses the prototype chain hence hasOwnProperty returning false (I am simplifying this greatly). You can do one of two things: use toObject() to convert it to a plain object and then your checks will...

Node.js app giving ERR_EMPTY_RESPONSE

javascript,node.js,mongodb,npm

//The route for getting data for the database app.get("/database", function(req, res) { Entry.find({}, function(err, data) {console.log(err, data, data.length); }); }); //The route for posting data on the database app.post("/database", function(req, res) { //test new post var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'}); newMonth.save(function(err) { if (err !== null) {...

How to add new items to an array in MongoDB

arrays,node.js,mongodb

$set is not an array update operation. The $set operator replaces the value of a field with the specified value. You just want to use $push by itself, as in .update({_id: id}, {$push: {name: item}}) You can't interpolate object property names in raw object declarations, so if you want to...

Incorrect response to mapReduce query in mongo-db

mongodb,mapreduce

Your problem here is that you have missed one of the core concepts of how mapReduce works. The relevant documentation that explains this is found here: MongoDB can invoke the reduce function more than once for the same key. In this case, the previous output from the reduce function for...

Mongoose : update collection with previous data

node.js,mongodb,mongoose

First of all the schema you posted is off, should be { album : "album1", pictures: [ 1.jpg, 2.jpg, 3.jpg ] } note "pictures" is an array not an object. You can add to the array with //SAVE DB AlbumPhoto.update({album:'album1'}, {$push: {pictures: "new.jpg"}}, function(err, data){ if(err){ console.log(err); } }) ...

mongodb populate method not working

node.js,mongodb,model,populate,auto-populate

When you create an instance of the Post model, you need to assign the _id from the user as an ObjectId, not a string: var ObjectId = require('mongoose').Types.ObjectId; Post.create({ text: 'farheen123', created_by: new ObjectId('5587bb520462367a17f242d2') }, function(err, post) { if(err) console.log("Farheen has got error"+err); else console.log(post); }); ...

MongoDB. Index was out of range

c#,mongodb,mongodb-csharp

You mention in the comments that the underlying issue is an OutOfMemoryException. Answer here suggests paging best practices MongoDB - paging...

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

mongodb

It's not "documents" it's "Objects" as is stated, but you would not be the first person to not fully understand the .explain() output. Put simply, you have as part of your index an "array" element (actually the maximum "two" allowed), which means that your index is what we call "MultiKey"....

Query not working - MongoDB

mongodb

Looks like you've missed some brackets before $elemMatch: db.items.find( { "$or": [ {"f": {$elemMatch: {"t": "ry", "v": {$gt: 1980}}}}, {"f": {$elemMatch: {"t": "g", "v": {$in: ["Drama"]}}}} ] } ) ...

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

mongodb,mongodb-query

Yes, Changes made to data in MongoDB shell are permanent but for configuration parameters, they will last only till next restart of instance if they are not specified in config file. MongoDB runs with default values if config file is not specified. You can specify config file as, mongod --config...

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

node.js,mongodb

JavaScript has no nice notation for creating an object where the keys are variables: var $push_query = {}; $push_query[name] = item; ... {"$push": $push_query} ... ...

MongoDB explain() cursor field

mongodb

explain() output changed in 3.0. "Theirs" is <3.0 output.

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

javascript,node.js,mongodb

Since you're using the mongojs module, you're going to have to connect to the database using the following method db = mongo("127.0.0.1:27017/"+db, collections); ...

mongoexport fields from subdocuments to csv

mongodb

There is mistake in your syntax. From mongo version 3.0.0, mongoexport removed the --type = csv option. Use the --type=csv option to specify CSV format for the output. You should use : mongoexport --db tests --collection accounts --type=csv --fields account_number,situses --out coordinates.csv For nested fields you should use : mongoexport...

how give different privilege for user and admin in mongodb

javascript,mongodb,mongoose,sails.js

I want to give the different privileges for each of user Super admin can access whole DB. Admin can access the data relate to that field User can access the data related to the user. What you need is primarily a document-level access control where a user can access...

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

database,node.js,mongodb,mongoose,mongolab

Try using db = mongoose.connect(uri); instead of db = mongoose.createConnection(uri); ...

c# mongodb driver groupby

c#,mongodb,mongodb-csharp

I think the driver just doesn't implement the Linq GroupBy method. Use aggregate framework instead. You can find good examples here - MongoDB Aggregation Framework Examples in C# You don't need to link any new libraries the support for the aggregation framework goes with MongoDB C# driver. Hope it helps!...

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

database,mongodb,sorting

No. Well, not exactly. A db.collection.find() will give you the documents in the order they appear in the datafiles host of the times, though this isn't guaranteed. Result Ordering Unless you specify the sort() method or use the $near operator, MongoDB does not guarantee the order of query results. As...

Do you get the same performance using index prefixes?

performance,mongodb,indexing

A "compound index" which is the correct term for your "link" does not create any performance problems on "read" ( since writing new entries is obviously more information ) than an index just on the single field used in the query. With one exception. If you use a "multi-Key" index...

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

javascript,node.js,mongodb

That's a pretty wide question, partly opinion based. This question should be closed, but I still want to give you some advice. There once was the Active Record pattern, which has been proven to be pretty difficult to maintain. The solution was the DAO pattern, but this adds a lot...

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

arrays,node.js,mongodb,mongoose,schema

You can use the distinct function to get the unique values across all category array fields of all documents: Article.distinct('category', function(err, categories) { // categories is an array of the unique category values }); Put an index on category for best performance....

Handling Custom BSON Marshaling (Golang & mgo)

json,mongodb,go,bson

Custom bson Marshalling/Unmarshalling works nearly the same way, you have to implement the Getter and Setter interfaces respectively Something like this should work : type Currency struct { value decimal.Decimal //The actual value of the currency. currencyCode string //The ISO currency code. } // GetBSON implements bson.Getter. func (c Currency)...

Is it possible to perform two commands in the console MongoDB

mongodb

show dbs is a simple helper. You should use: db.getMongo().getDBs(); So db.getMongo().setSlaveOk();db.getMongo().getDBs() should work....

Why won't mgo unmarshall my struct properly?

mongodb,go,bson,mgo

The GetBSON method should return the value to be marshaled, not the binary data resulting from marshaling it. That's why its first result type is interface{} and not []byte.

push item in sub document

mongodb,mongodb-query

You need the positional $ operator in your update portion of the statement: db.getCollection('forms').update( { "_id" : ObjectId("557e8c93a6df1a22041e0879"), "Questions._id" : ObjectId("557e8c9fa6df1a22041e087b") }, { "$push" : { "Questions.$.DataSource" : { "_id" : ObjectId("557e8e5ea6df1a27b403ff6b"), "CreationDate" : ISODate("2015-06-15T08:35:42.923Z"), "IsActive" : true, "Text" : "op", "Value" : "op" } } } ) It identifies...

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

mongodb,sails-mongo

Attention: Mongo id should be unique as possible in order to scale well. The default ObjectId is consist of a timestamp, machine ID, process ID and a random incrementing value. Leaving it with only the latter would make it collision prone. However, sometimes you badly want to prettify the never-ending...

How could I get the matched nested items in array

mongodb

You should first $unwind records and then match elements like following: db.collection.aggregate({ "$unwind": "$records" }, { "$match": { "records.items": { "$in": ["A428 ", "A429 "] } } }, { "$group": { "_id": "$_id", "records": { "$push": "$records" } } }).pretty() ...

Use JSON file to insert data in database

javascript,json,mongodb,meteor,data

Simple use underscores _.extend function. Like this: var newProfile = _.extend( JSON.parse(Assets.getText('test.json')), {user: id} ) Profiles.insert(newProfile) ...

Data not visible in mongoDB when inserted from PyMongo

python,mongodb,pymongo

Your code "works' but I think you may have copied-and-pasted something wrong. In particular, you're swapping the use of find() and find_one(). The enter_data() method calls insert() without specifying _id so the driver will invent one for you. That _id ends up being an ObjectId similar to this: { "_id"...

Mysql InnoDB vs Mongodb write performance

mysql,mongodb

innodb_flush_log_at_trx_commit = 2 Is the winner : 150x faster !!! on standard disk (will try on SSD later)...

Order records by mapping collections

mongodb,mongodb-query

As per your output you should required only aggregation on Book collection and the aggregation query as below : db.book.aggregate({ "$group": { "_id": "$authorId", "names": { "$push": "$name" }, "count": { "$sum": 1 } } }, { "$unwind": "$names" }, { "$sort": { "count": 1 } }, { "$project": {...

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

mongodb,spring-data,objectid

So after searching for an hour, I have found the solution - i had to look at this post which is not in java but in node.js. Querying a MongoDB based on Mongo ID in a node.js app Thankfully, the language is close to java so I saw that you...

How to remove duplicate values inside a list in mongodb

mongodb,mongodb-query,pymongo,aggregation-framework

Well's you can do this using the aggregation framework as follows: collection.aggregate([ { "$project": { "name": 1, "code": 1, "abbreviation": 1, "bill_codes": { "$setUnion": [ "$bill_codes", [] ] } }} ]) The $setUnion operator is a "set" operator, therefore to make a "set" then only the "unique" items are kept...

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

c#,mongodb,nosql,document,bson

Reason of error is BsonRepresentation attribute on array properties. You should remove it. Moreover you can remove BsonRepresentation from all properties.

using MongoDB aggregate count subdata

mongodb,aggregate

please try the below query : db.collection.aggregate( [ { "$unwind": "$data.order_goods" }, { "$group" : { "_id" : "$data.order_goods.category", "total": {"$sum":1} } }, { "$project" : { "category" : "$_id" , total : 1 } ] ); ...

Working with embedded documents in MongoDB

javascript,mongodb,meteor

In keeping with your current schema (not recommended): First, save the entire document to the client: doc = { _id: 1, projectName: name, managers: [ { managerId: "manager1", status: false, startDate: "startDate", endDate: "endDate" }, { managerId: "manager2", status: false, startDate: "startDate",endDate: "endDate" }, { managerId: "manager3", status: true, startDate:...

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

java,spring,mongodb,spring-data-mongodb

Per MongoDB reference for $or, your Query should be @Query("{'$or':[ {'type':?0}, {'name':?1} ]}") you'll need to give pass type and name params....

AngularJS factory dependencies

javascript,html,angularjs,mongodb

DOCS Change your factory to service as you are using this factory return an object or primitive type not bind with this app.services('articleFactory', ['$q', '$http', function ($q, $http){ this.getAllArticles = function (){ var deferred = $q.defer(), httpPromise = $http.get ('/entries'); httpPromise.success (function (data){ deferred.resolve (data); }) .error (function (err){ console.log...

Convert string to ISODate in MongoDB

javascript,python,mongodb,date

If you can be assured of the format of the input date string AND you are just trying to get a count of unique YYYYMMDD, then just $project the substring and group on it: var data = [ { "name": "buzz", "d1": "2015-06-16T17:50:30.081Z"}, { "name": "matt", "d1": "2018-06-16T17:50:30.081Z"}, { "name":...

How to add a subdocument in a mongoose schema

javascript,node.js,mongodb,mongoose

Since the address field is not required by Mongoose when you retrieve the Model from the database the field just won't be defined. Thus you won't be able to add an address field. You should check to see if it exists if(member.address === undefined){ member.address.push(new_address); } else{ member.address = [new_address];...

Meteor - Query Embedded Documents

javascript,mongodb,meteor

Use fields (?): return MyCollection.find({},{fields:{"MWLink.LinkID": 1}}).fetch(); If you feel you need a bit more power on what comes up you can use map (?) or a transform (?): var transform = function(doc) { return { MWLink : { LinkID: doc.MWLink.LinkID } } } //A transform returns a cursor return MyCollection.find({},...

Conditionally group and sum of the elements from an array

java,mongodb,mongodb-query,mangodb

You should use aggregation to get result. If you want ActionType wise OrderCount for given date (particular) date then you need to first match start to your date and then group data according to Action.Type. The query will be as following: db.collection.aggregate({ $match: { "SessionTimeStamp.Start": ISODate("2015-06-02T05:36:49.045Z") } }, { $group:...

mongodb bind ip won't work unless set to 0.0.0.0

mongodb

You can bind mongod only to one IP, with 0.0.0.0 being the alias for "listen on all available network interfaces". So either use bind_ip=127.0.0.1 to listen to the loop back interface or bind_ip=<someIP> to listen to that IP only or bind_ip=0.0.0.0 to listen to all available IPs on the system....

DB relationship: implementing a conversation

mongodb,meteor

It all depends on usage patterns. First, you normalize: 1 conversation has many messages, 1 message belongs to 1 conversation. That means you've got a 1-to-many (1:M) relationship between conversations and messages. In a 1:M relationship, the SQL standard is to assign the "1" as a foreign key to each...

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

mongodb,mongodb-csharp

BsonDocument provides flexible way to represent JSON/BSON in C#. Creating BsonDocument is similar to creating JSON objects. Simple document new BsonDocument("name", "Joe") creates JSON { "name" : "Joe" } More complex document new BsonDocument { {"Name", "Joe"}, { "Books", new BsonArray(new[] { new BsonDocument("Name", "Book1"), new BsonDocument("Name", "Book2") }) }...

MongoDB Java Driver 3.0 MapReduce

mongodb,mongodb-java

Yes, this is the expected behavior. Since the MapReduceIterable is a fluent interface, there must be some way to signal the driver that it's time to actually do the map-reduce, and currently the only way to do that is to start iterating. If you really don't need the results, and...

MongoDB: find documents with a given array of subdocuments

arrays,mongodb,find,aggregate,subdocument

What you are asking for here is a little different from a standard query. In fact you are asking for where the "name" and "lastname" is found in that combination in your array two times or more to identify that document. Standard query arguments do not match "how many times"...

MongoJS - No Error On Unique Index

mongodb,mongojs

This seems to be a "buggy" response from mongojs which likely results from it's implementation of returning the "inserted" object as a response. The "core" driver does not do this but would either return a "ok" response or an error: var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost/test', function(err,db) { var collection =...

Query an array of embedded documents in mongodb

mongodb,embedded-documents

You can push the item into the array with the following command: db.mycollection.update({ _id: "zinfandel", "last_search.engine": { $nin: ["notwellknownengine.com"] } }, { $push: { "last_search": { "engine" : "notwellknownengine.com", "query" : "stackoveflow.com" } } }); ...

Find Mongoid geospacial circles that contain a point

mongodb,mongoid,geospatial

Modelling a "circle" is a valid approach by specifying a "centre" and a "radius", but finding things "within the circle" is generally straightforward if not immediately obvious: Service.collection.aggregate([ # Get the distance from the current location { "$geoNear" => { "near" => { "type" => "Point", "coordinates" => [ 1,...

Converting an html page to binary format in python

python,html,mongodb,binary

The pymongo driver already has methods for importing strings as binary. Following with this example: import pymongo import bson.binary from pymonngo import MongoClient from bson.binary import Binary client = MongoClient() db = client.test db.btest.insert({ "bindata": Binary("Hello",0) }) db.btest.find_one() Which gives you: {u'_id': ObjectId('5582b33c268e1505371a5477'), u'bindata': Binary('Hello', 0)} Or from the mongo...

how to update array of object in mongodb with for loop

javascript,node.js,mongodb

Your problem is how you are trying to notate the object "keys". This isn't valid for key construction in JavaScript object as the key names are literal and all characters are considered part of the name string. Notate like this instead: var update = { "rate": minRate }; update["classifierCategories."+e+".rate"] =...

How can i insert current date in robomongo?

java,mongodb,robomongo

db.yourcollection.insert({date_field_name:new Date()})

mongoose won't update object field

mongodb

Try using _.extend or _.assign instead: var updated = _.assign(form, req.body); This answer by ShitalShah highlights the differences between merge and extend: Here's how extend/assign works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their...

How to update and read a collection in MongoDB using Mongoose

javascript,node.js,mongodb,mongoose

Your GET request should have worked because a browser executes a GET request by default. Try the following. app.get("/database", function(req, res) { Entry.find(function(err, data) { if(err) { console.log(err); } else { console.log(data); } }); }); As far as testing your POST route is concerned, install a plugin for Google Chrome...

add subitems to meteor document

mongodb,meteor,collections,insert-update

Give something like this a try: // fetch the current list var list = Lists.findOne(_currentListId); // find the number of existing items and handle the case where there are none var numItems = (list.items || []).length; // the the next item key will be one more than the length var...

mongodb aggregate unwind array and no array

arrays,mongodb,aggregation-framework

This basically does what you want with some help from $cond and $ifNull: db.collection.aggregate([ { "$project": { "x": 1, "y": { "$cond": [ { "$ifNull": [ "$y.0", null] }, "$y", { "$map": { "input": ["A"], "as": "el", "in": "$y" }} ] } }} ]) So those first conditions work out...

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

mongodb

The query needs to match on the _id (at least that is what it appears you are trying to match on). The update value for resetPasswordExpires is not a property of roles. Something like the following should work: db.users.update( { _id: ObjectId("000") }, {$set: { "resetPasswordExpires": ISODate("2015-06-20T18:04:40.014Z")} }); ...

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

node.js,mongodb

You have to use the serverStatus database command to retrieve the version of the mongod or mongos instance you're connected to. The native node.js driver provides the Admin.serverStatus for that purpose: var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost:27017/test' var conn = MongoClient.connect(url, function(err, db) { var adminDb = db.admin();...

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

node.js,mongodb,mongoose

You need to convert the string _id to a valid Mongodb ID var mongo = require('mongodb'), BSON = mongo.BSONPure, groupid = new BSON.ObjectID(req.headers['groupid']); Cloud.find({'_id': groupid}).exec(function(err, data) { if(err){ res.status(404); res.json('group not found'); } else { // Do Stuff } }); If you use Mongoose you can convert the string to...

Live Preview Iframe

javascript,node.js,mongodb,iframe

I wouldn't build it entirely on Node.js I would rather use the power of the modern client-side Javascript and move some logic there with persisting some of the data coming from the server. This way I can lower the number of requests and make my script more flexible. Two libraries...

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

c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0

The query you need to perform uses the $elemMatch query operator. So, this query using a lambda expression var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123")); Is equivalent to this query using the FilterDefinitionBuilder: var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch( foo => foo.Bars, foobar => foobar.BarId == "123")); ...

Mongoose population in instance methods

node.js,mongodb,mongoose,mongoose-populate

In Mongoose instance methods, this is the document instance the method is being called on, so you can do this as: MainSchema.methods = { retrieveChilds: function(callback) { this.deepPopulate('childs.subject.data', callback); }, }; Then to call it: main.retrieveChilds(function(err, _main) { // _main is the same doc instance as main and is populated....

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

javascript,mongodb,meteor

Something like this should work: 'submit form' : function(event){ event.preventDefault(); var query=document.getElementsByClassName("twilioProcessorsms")[0].value; var valueToInsert = { sms: esms }; valueToInsert[query] = { accountSID: accsid, authToken: token, phoneNumber: phno} }; ChoiceList.insert(valueToInsert); ...

ObjectID not storing hexadecimal value

javascript,node.js,mongodb,sails.js,waterline

Answering my own question! Seemed to be something goofy happening with the brew installation of MongoDB. Manually re-installing it from http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/ and then restoring my backed up database seemed to do the trick. I'd still love to know from a from a code/technical standpoint why my environment suddenly decided to...

Creating unique Mongoose objects from CSV

javascript,node.js,mongodb,csv,mongoose

You can use async's eachSeries method. I assume that output is an array of users. Async's eachSeries will iterate over an array, process an item and, once the callback method is called, go to the next item in array : fs.readFile(file, function(err, data) { if (err) throw err; parse(data, function(err,...

Mongoose installation failed on Mac

node.js,mongodb,mongoose

From what I see in your terminal, I think your installation for mongoose is successful. And you are staring your application using nodemon but I think that is not installed as you are getting an error nodemon: command not found. So first you will need to install nodemon using, npm...

Sorting a collection in doctrine2

php,mongodb,doctrine2,doctrine,odm

Pretty sure sort takes an array argument. Try ->sort(['r' => 'desc]); I looked it up... http://apigen.juzna.cz/doc/doctrine/mongodb/source-class-Doctrine.MongoDB.Cursor.html#564-585...

Creating index while updating the documents

mongodb,indexing

The amount of time it takes to add the index would depend on your hardware, but with 20206 records a simple index as you describe shouldn't take very long for most hardware. Queries fully covered by the index (i.e. where you specify A and B, or just A, but not...

Testing motor.MotorClient() connection

mongodb,tornado-motor

Generally, the answer is don't. Don't check if a connection to MongoDB is working. You might find out that it's working right now, but the next operation might fail anyway--your sysadmin might pull your cable, the server crashes, whatever. Since you need to handle errors later in your application no...

Cassandra data model to store embedded documents

mongodb,database-design,cassandra

If your document nesting level is not too deep, you can use User Defined Types from C* 2.1. I personally suggest to rethink your schema into more flat form like: create table profiles ( name text, name2 text, email text, username text, ts timestamp, primary key (name,name2) // compound primary...

MongoDb c# bad unknown operator exception

c#,mongodb,mongodb-csharp

That isn't a valid query. While you can add $orderby that way (but it's not recommended), skip and limit are not part of the document. Best thing to do is to not try to build it that way and instead let the driver build it for you. This will also...

How to defer reading until writing is done?

javascript,node.js,mongodb,websocket,socket.io

In a multiplayer game, you need to do important state logic on the server, or at least do some sort of state validation on the server side. You are only noticing this "hack" because it is easy to do. You have to design your multiplayer server to be resistant against...

MongoDB, How to query subdocuments close to specific location?

node.js,mongodb,geojson

As stated, the closest you can get to this with your current structure is using $geoNear which is an aggregation framework operator. This has the necessary projection needs required to resolve the "match" from the sub-documents. But first a reworking of your sample without the errors: { "firstName": "firstname", "phone":...

paging subdocument in mongodb subdocument

mongodb,mongodb-query

Though this is possible to do with some real wrangling you would be best off changing the document structure to "flatten" the array entries into a single array. The main reason for this is "updates" which are not atomically supported by MongoDB with respect to updating the "inner" array due...

How update the first element of an array in mongoDB?

node.js,mongodb,mongoose

If you set pictures to an empty array you shouldn't have a value at index 0. var albumData = { album : 'album1', pictures : [] };...

How to check if multiple documents exist

mongodb,mongodb-query

You are looking for the $in-operator. db.collection.find({ id: { $in: { [ 1, 3 ] } }); This will get you any documents where the id-field (different from the special _id field) is 1 or 3. When you only want the values of the id field and not the whole...

Download of GridFs using nodejs does not start

node.js,mongodb,gridfs,gridfs-stream

change gfs.exist({_id: id}, function (err, found) { if (err) return handleError(err); if (!found) res.send('Error on the database looking for the file.') }); var readStream = gfs.createReadStream({ _id: id }).pipe(res); to gfs.exist({_id: id}, function (err, found) { if (err) return handleError(err); if (!found) return res.send('Error on the database looking for the...

Exclude _id field in mongodb while inserting

mongodb

No, you can't. The _id field is required for internal purposes in MongoDB. It is the MongoDB equivalent to a primary key in a relational database. Every document must have an unique _id field. It does not necessarily need to be an ObjectId, but it must be a value unique...

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

ruby-on-rails,mongodb,mongoid,nomethoderror

Apparently the way to fix this is to remove the has_many :vessels from Owner and has_many: modifications from Vessel, so that the resulting code looks like: class Owner include Mongoid::Document field :name, type: String field :uprn, type: String end class Vessel include Mongoid::Document belongs_to :owner field :name, type: String attr_accessor...

Projection with single child object

mongodb,projection

You can access fields inside an embedded document using the dot notation. Don't forget to quote the field name though. > db.collection.find() { "_id" : 1, "semester" : 1, "grades" : { "student1" : 70, "student2" : 85 } } { "_id" : 2, "semester" : 2, "grades" : {...

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

c#,arrays,mongodb,subset,mongodb-csharp

Use mongo Set Operator using $setIsSubset in aggregation you will get your result, check following query : db.collectionName.aggregate({ "$project": { "Name": 1, "Tags": 1, "match": { "$setIsSubset": ["$Tags", ["A", "B", "C"]] //check Tags is subset of given array in your case array is ["A","B","C"] } } }, { "$match": {...

Inserting a variable in MongoDB specifying _id field

python,mongodb,pymongo

Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...

Async await usage for MongoDB repository

c#,mongodb,asynchronous,parallel-processing,async-await

When you call an async method you should await the returned task, which you can only do in an async method, etc. Awaiting the task makes sure you continue execution only after the operation completed, otherwise the operation and the code after it would run concurrently. So your code should...

Null set returned by mongodb aggregate Cursor in PHP

php,mongodb,mongodb-query,pymongo

Try to generate a MongoDate() object as follows $dateFrom = new MongoDate(strtotime("2015-06-01T00:00:00Z")); $dateTo = new MongoDate(strtotime("2015-06-03T00:00:00Z")); which you can then use in your aggregation pipeline instead of the MongoDB ISODate objects in your PHP query. /* Run the command cursor */ $result = $collection->aggregateCursor( [ [ '$match' => [ 'date'=>...

Compare Array with Collection-Array containing Objects

node.js,mongodb,mongoose,schema

You can try this: objectModel.find({ 'members.user_id' : {'$in' : ['asdf123lkd', 'asdf1223']} }, function(err, data) { console.log(err,data); }) ...

How to query a Document by ObjectId with rmongodb

r,mongodb,rmongodb

This should work: result <- mongo.find(Connexion, "db.col", query=list('_id' = mongo.oid.from.string("5571849db1969e0a6eb32731"))) ...

Meteor/MongoDB limiting the result

mongodb,meteor

Meteor's collection API is somewhat different from that of the mongo API. find takes up to two parameters: a selector object, and an options object. options allows you to specify such things as sort, skip, limit and fields, in addition to the meteor-specific reactive and transform.

Get matching elements in mongodb array

php,mongodb,aggregation,pipeline

It's true that the "standard projection" operations available to MongoDB methods such as .find() will only return at most a "single matching element" from the array to that is queried by either the positional $ operator form in the "query" portion or the $elemMatch in the "projection" portion. In order...

mongoDB query with case insensitive schema element

mongodb,nosql

We can search the element value using case insensitive [...] Is there [something] similar for schema element [?] No. We may assume that JavaScript and JSON are case sensitive, and so are MongoDB queries. That being said, internally MongoDB uses BSON, and the specs say nothing about case-sensitivity of...

Mongo Collection Find By Id with Filter

c#,mongodb,mongodb-query

Generic Type of Builder should be the same as for collection's generic type. In your case collection should have type BsonDocument. var _collection = database..GetCollection<BsonDocument>("name"); var filter = Builders<BsonDocument>.Filter.Eq("_id", id); var result = _collection.Find(filter); ...

google maps refresh without displaying gray

javascript,jquery,mongodb,google-maps,google-maps-api-3

You can first set the visibility of the div which contains map to hidden; then listen to the first tilesloaded event, and set the visibility back to visible. Doing this the Maps should only pop up after all it tiles is loaded (so no gray screen) Here is a quick...

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

javascript,json,mongodb,meteor

JS Template.test.helpers({ itemsArray: function(){ // This would normally be the result of your Mongo query var itemsArray = [ { "_id": "SXTJBs7QLXoyMFGpK", "Brand": "Nike", "Material": "Cooton", "Price": "67484", "ComboId": "y23", "Color": "White", "LaunchDate": "08/02/2015", "DiscountActiveDate": "08/03/2015", "DiscountInactiveDate": "08/04/2015", "Category": "Sport", "ProductSubCategory": "trackpant", "Status": "Pending", "TemplateID": "557fc7d06ecb48d38a67a380" }, { "_id": "IGJHihljiUYG6787y",...