Questions tagged [mongodb]

42860 questions
0

votes
1

answer
7

Views

One out of two Document property not inserted in a mongoDB collection using: Mongoose and ExpressJS

A Nodejs server application gets Name and Age from an HTML form (with post method) and with the help of ExpressJS and Mongoose has to create a MongoDB document. That works but Age is not written in the document of the collection. Please help me to fix it. Here are the files with the code: personform...
user374324
1

votes
1

answer
1.4k

Views

MongoDB, does MaxPoolSize limit applies to all the client instances?

I increased MaxPoolSize value to 3000. does this mean that there are 3000 concurrent connections allowed using this instance, or it counts any other connections through other object instances too? var connectionString = 'mongodb://username:[email protected]:27017/MyDB?maxPoolSize=3000' var client = new Mo...
Blendester
1

votes
3

answer
202

Views

How to load asynchronous database url and initiate database connection before express.js app starts?

I have configured the express.js app to run on AWS lambda. The database URL is stored and encrypted in the Amazon KMS service so if I want to use the URL then I have to decrypt the key using AWS KMS service. // imports import mongoose from 'mongoose'; import serverless from 'serverless-http'; // KMS...
sym
1

votes
1

answer
811

Views

Can't connect to mongo docker image with mongoose

I'm trying to run a simple docker setup with node and mongo: Dockerfile: FROM node:8.9.4-alpine RUN mkdir /app WORKDIR /app COPY package.json /app/ COPY package-lock.json /app/ RUN npm install ADD . /app/ docker-compose.yml: version: '3' services: db: image: 'mongo' ports: - '27017:27017' api: build...
Philip Feldmann
1

votes
2

answer
687

Views

MongoDB : Can't insert twice the same document

On my pymongo code, inserting twice the same doc raises an error : document = {'auteur' : 'romain', 'text' : 'premier post', 'tag' : 'test2', 'date' : datetime.datetime.utcnow()} collection.insert_one(document) collection.insert_one(document) raises : DuplicateKeyError: E11000 duplicate key error c...
Romain Jouin
1

votes
2

answer
195

Views

How to insert an object in an array using Mongo shell commands?

I have to insert an object {'category' : 'Vehicle'} in the rated array below using Mongo shell commands. How can I do that? { 'rating': { 'userid': 1234, 'bookingid': 4567, 'rated': [ { '_id': '5aaa356f6b992b2068a1b691', 'category': 'Driver', 'comment': 'Good', 'rating': 5 }, { '_id': '5aaa356f6b992...
Suhaib
1

votes
1

answer
233

Views

TypeError: callback.apply is not a function after allowDiskUse

I have a collection having 1Million documents... I have passed the option for allowDiskUse and now it is throwing error TypeError: callback.apply is not a function I have searched for this but could get the solution... Please help const pictures = await Picture.aggregate([ { $sort: { createdAt: -1 }...
Anthony Winzlet
1

votes
1

answer
962

Views

mongo - dropping non existant collection throws 'ns not found'

I'm trying to drop a non existant collection and I get the following error: MongoError: ns not found. In a similar question, there is a link to the mongo code which shows that this is the expected behaviour: MongoError: ns not found when try to drop collection However, according to the mongo documen...
ayun12
0

votes
0

answer
4

Views

How to change property of newly created collection on click

I am creating a new collection from current schema with same properties. I am using nodemailer to verify email by setting a schema key to value true upon clicking the link. It is happening successfully if changing value of current schema from this code:- router.get('/verify',function(req,res){ con...
NoobCoder
1

votes
3

answer
49

Views

How to make lookup between two collections when an item in an array exists in the other collection?

In Lookup with a pipeline, I would like to get the linked records from an array in the parent document. // Orders [{ '_id' : ObjectId('5b5b91a25c68de2538620689'), 'Name' : 'Test', 'Products' : [ ObjectId('5b5b919a5c68de2538620688'), ObjectId('5b5b925a5c68de2538621a15') ] }] // Products [ { '_id'...
Homam
1

votes
2

answer
148

Views

How to get entire MongoDB collection with PHP

Using the following code, I can grab a node from a collection: However, what I'm really looking to do is get everything from the DBCOLLECTION. I'm kind of at a loss on how to do this. A few searches either go over my head or are for older versions of the PHP driver, such as this one fetch all data...
lowcrawler
1

votes
4

answer
819

Views

MongoDB regex string startswith and endswith [duplicate]

This question already has an answer here: Regex matching beginning AND end strings 4 answers Regular Expression to find string starts with letter and ends with slash / 3 answers So i have something that looks like this db.usuarios.insert ( [ { 'nome' : 'neymala', 'idade' : 40, 'status' : 'solteir...
user56130
1

votes
1

answer
78

Views

MongoDB one-to-many - array of IDs or ID ref on child model? [closed]

Specifically, I'm thinking of a chat app, where a User has many Chats and each Chat has many Messages. How would I express the Chat --has-Many--> Message relationship? Initially, I thought I'd store the list of Message ID references on Chat, e.g. a Chat document could look something like { _id: Obje...
Code Jockey
0

votes
0

answer
4

Views

Is there update operator support on MongoDB connector for Spark?

Using: Spark / MongoDB connector for Spark / Scala Hi Is there update operators support on MongoDB connector for Spark? I'd like to use update docuemnt query(updateOne query) with $inc, $currentDate, $setOnInsert update operators and update option(like upsert = true). I already did with mongo-scala...
gingermanjh
0

votes
0

answer
6

Views

TypeError: Cannot read property 'findOne' of undefined from Passport

I have implemented a Passport login feature in Node.js. I try to log in using LocalStrategy, but I get an TypeError: Cannot read property 'findOne' of undefined. I think there is a problem with findOne in the async try part of LocalStrategy.js. But I do not know what the problem is. Is there somethi...
COLEAN
1

votes
1

answer
636

Views

Mongo-Go-Driver Failing to Connect

So I am trying to use https://github.com/mongodb/mongo-go-driver to connect to a mongo database in golang. Here is my connection handler: var DB *mongo.Database func CreateConnectionHandler()(*mongo.Database, error){ fmt.Println('inside createConnection in database package') godotenv.Load() fmt.Pri...
Peter Weyand
1

votes
1

answer
24

Views

How to query an array for different combinations of ANDs and ORs in MongoDB Aggregation?

I am trying to search for list of students who have completed courses using different combinations of Logical ANDs and ORs. For example I want to get student who completed ('Course 1' and 'Course 2') or 'Course 3' Here is my data structure for each student : { '_id' : ObjectId('5c68841cb6b18f31975c...
Badis Merabet
1

votes
2

answer
517

Views

MongoDb use filter to match a list

I have a list of BsonDocument: var list = db.GetCollection(collectionName); var myIds = list.Find(_ => true) .Project(Builders.Projection.Include('_id')) .ToList(); that contains: myIds = '{ { '_id' : 'cc9d9282-c9d2-4cba-a776-ffddsds274d5' }, { '_id' : '2c1ddd82-c9d2-4dda-afr6-d79ff1274d56' },...
DanielV
1

votes
2

answer
27

Views

Correct way to figure out what rejection a promise had?

I have an API / express router: router.post('/signup', async function (req, res) { try { var user = await controllers.user.register(req.body.username, req.body.password); req.session.user = user; res.json(user); } catch (e) { res.status(500).json('DB Error'); } }); Currently, on error, it returns 50...
user2719875
1

votes
1

answer
30

Views

Sum all named fields in aggregation

I am trying to calculate the sum of all the values below. I have tried googling the question in different ways but cannot find an answer. The data looks like this. I don't care about the keys, I am just looking for a total of the values for monday 'monday' : { 'a' : 5, 'b' : 2, 'c' : 1, 'd' : 2, 'e...
MC101
1

votes
2

answer
19

Views

MongoDB issue in query returning value from user

I am using MongoDB with Nodejs and I am trying to find the usertype value of a specific user so I've got this: var myQuery= { username: req.body.username }, { 'usertype': 1 }; dbo.collection('usercollection').find(myQuery, function(err, obj) { ... What I need returned is the value of usertype from t...
monroe2019
1

votes
2

answer
35

Views

Mongodb aggregates: how to project a formatted filter

I think it's not a difficult question but I'm not sure how to do it My collection is [ { type:'bananas', weight:'1'}, { type:'bananas', weight:'10'}, { type:'apple', weight:'5'} ] The result I would like to have is the count of each type in the same query, result expected: { bananas: 2, apple: 1 } W...
François Richard
1

votes
1

answer
28

Views

How to insert an interface{} type to mongodb with bulk.Insert()

I can't insert a big array into my collection; I have a problem with the interface{} type. Here's the code: collections = getSession().DB('go').C('comments') func BenchmarkBulkInsert(data interface{}) { bulk := collections.Bulk() bulk.Insert(data...) _, bulkErr := bulk.Run() if bulkErr != nil { pani...
Hernan Humaña
1

votes
2

answer
47

Views

Laravel Moloquent. Add projection to related model

I have a query with relation. $dbQuery = $this->someModel ->where('user_id', '', Auth::id()) ->with(['questions']) ->get(['title', 'status', 'expired_at']); The list of fields in get() method define the list of selected fields for the top level of selected data. But I need also add a projection to q...
Denys Siebov
1

votes
1

answer
37

Views

MongoDB - how unpack object?

document: {'_id':'5cb0dfe234a8a30c9c0af127', 'sensors': [{'value0':0.153, 'value1':-0.306, 'value2':9.807}], 'timestamp':1555095522489,'__v':0} I want to get 4 field (timestamp and value 0..2) without any array / object. unwind work only against array but not objects. What should I do? desired outpu...
Dmitry Sokolov
1

votes
1

answer
33

Views

The same default value gets used every time by `new mongoose.Schema`

I have problem using uuid with new mongoose.Schema. I use it to generate unique key for a device and save it to the MongoDb using Node.js. the problem is that it uses the same UUID every time. This is the model: const mongoose = require('mongoose'); const uuid = require('uuid/v4'); const DeviceSchem...
Banana Cake
1

votes
3

answer
18

Views

How to query a document with the highest value of a field

Let's say I have a collection of documents. To make this simpler, let's say all these documents have just 2 fields, name and id, like below. I want to get the document with the greatest value of 'id'. Can I use the .find({}) with some parameters? If so, I can't figure out which parameter would find...
lakers5824
1

votes
3

answer
107

Views

Failure to connect to configured mongo instance (Connection refused)

Based on this guide: https://docs.opsmanager.mongodb.com/current/tutorial/install-simple-test-deployment/ I am installing MongoDB and MongoDB Manager. I have created a docker image for each application and start them on the same virtual network: docker network create --driver bridge mongo-network wi...
u123
1

votes
3

answer
4.5k

Views

Finding first 20 documents from collection in mongodb

I want to display first 20 records from collection on one Jframe and next 20 on another frame . I am newbie to MongoDB. please suggest a query to find first 20 and next 20 documents.
Prashant Thorat
-1

votes
0

answer
4

Views

Mongoose/Mongo: A query to find all documents older than five minutes?

I need mongoose to run a query that finds documents older than an amount of time described in milliseconds found in the config folder. This amount of time is stored like this, keys.anAmountOfMilliseconds Thus far, I've been able to pull all documents created in between NOW and FIVE minutes as descr...
ThirdGhostHand
1

votes
1

answer
3.4k

Views

Check if value exist in mongo collection

I'm working in node js and I'm using mongo (Im absolute beginner) . Now I need to have collection that basically needs to look like this array var keys = ['key1','key2','key3'] // with this I easily can check if some value I have exist in this array with indexOf function , Now I need to make coll...
user3237500
1

votes
2

answer
578

Views

Mongodb distinct query with contains query

I have a mongo collection User which contains data like:- { id : 1, name : 'gaurav', skills : 'C++ HTML CSS' } when I am searching for all users that have C++ skill in it with the following query I am getting correct results as expected db.user.find({skills:{contains:'C++'}}); But when I am searchi...
Gaurav joshi
1

votes
2

answer
1.8k

Views

cursor.next() always returns “java.util.NoSuchElementException”

I am writing a program in java which reads query results from MongoDB. Below is the code (which gives an exception): if(output != null){ BasicDBObject whereQuery = new BasicDBObject(); DBCursor cursor = null; for (DBObject obj : output.results()) { String UserID = obj.get('UserID').toString(); where...
rakemen
0

votes
0

answer
8

Views

MongoDB/Mongoose: A query to find documents older than an amount of milliseconds?

I need to find and manipulate all documents older than a certain time. I'm quite lost as to how this query is supposed to be written. I understand that Mongo's ObjectID has a byte describing a document's time of creation, but I haven't yet figured out how to capture all data older than a specific am...
ThirdGhostHand
1

votes
4

answer
5.3k

Views

mongodb refusing connection in python

I am using windows8, for writing code I use IDLE. I tried to connect python to mongodb. But when trying to get collection name than it gives an error. ServerSelectionTimeoutError: localhost:20101: [Errno 10061] No connection could be made because the target machine actively refused it This is code f...
Bhautik Patel
1

votes
2

answer
31

Views

Ajax get request not getting response after 5 calls

I'm trying to get some information from the mongodb server to the frontend with ajax get request. Everything works fine except that if i try to call 5 times the javascript function, i dont get any response from my local server. I tried to put some console.log() in order to debug in the nodejs functi...
Dariush Mohandes
1

votes
5

answer
4.5k

Views

removing an object from a mongodb document

I have a document in Mongodb collection, where I want to remove an object, using title key. I tried using $unset, but it only removes the title key not the object to which it belongs. { '_id' : ObjectId('576b63d49d20504c1360f688'), 'books' : [ { 'art_id' : ObjectId('574e68e5ac9fbac82489b689'), 'tit...
learner
1

votes
2

answer
903

Views

Update all documents that matched a list of ids in one command

Is there a way to update all documents that matched a list of id's in just one command. Currently I have to loop each id to update var ids = [ '8007068113729', '8007068502622', '8007068505821', '0825646209804', '0880319084614', '4260041334885' ] ids.forEach(function(i){ db.listing.update({_id:i},{$s...
Wylan Osorio
1

votes
1

answer
830

Views

MongoDB Internal implementation of indexing ?

I Learn Lot of things About indexing and find some stuff from Hereenter link description here Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the qu...
nitesh singh
1

votes
1

answer
612

Views

How does addToSet determine a duplicate?

Say I have a document that contains an array named Months. Each element in the array has a int field indicating which month & year it refers to (yyyyMM), e.g. 201612, 201701, etc. Each such element also contains additional fields, pertaining to that particular month. e.g. int numOfItems, string Coun...
datps

View additional questions