FAQ Database Discussion Community


How to aggregate time series documents in mongodb

mongodb,mapreduce,time-series,mongodb-query,nosql-aggregation
i have a mongo sharded cluster where i save data from a virtual machines monitoring system (zabbix ecc). Now I want to get some information from the db, for example the avg memfree in the last 2 days of one vm. I read the tutorials about aggregation and also the...

mongoexport fails when I add --collection BrowserHistory

json,mongodb,mongodb-query,mongoexport
I am trying to mongoexport a collection named,BrowserHistory from my DB. I have tried doing this through SSH into my CentOS server and a local MongoDB install on my computer. I have MongoDB 2.6 installed. Note: I have obscured the server, etc. info The commands I have tried and results...

MongoDb Access array of objects with certain property

arrays,mongodb,mongodb-query,aggregation-framework
I have one document as follows: { user: 'hvt07', photos: [ { link: 'http://link.to.com/image1.jpg', isPrivate: true }, { link: 'http://link.to.com/image2.jpg', isPrivate: false } ] } I want to get all photos which are with: isPrivate: false I am using the following query: db.collection_name.find({ photos:{ $elemMatch:{isPrivate: false} } }).pretty() I have...

How to assign count to a document in a mongodb collection

mongodb,mongodb-query
I have a collection where each document has a word and they are unique throughout the collection. As per my requirement, I executed a script such that whenever I insert a word (document) which already exists, it doesn't get inserted. Now, in such cases I need to add count to...

Mongodb between query in java

java,mongodb,mongodb-query,spring-mongo
i want to read all records that are between col1(value) and col2(value) in mongodb. so i write this code but it not work correctly. How implement this query? my entity is : in my entity i suppose date as long because day or month no important for me. private long...

Mongo insert $currentDate in Java Driver

java,mongodb,mongodb-query
I've got a question about $currentDate What is the best way to insert a document in mongo db so that it contains the "server time" (like ''now()'' in some RDBMSs) using the Java Driver? For example, lest say I have a document like: { name : "John", birthday : <$currentDate_goes_here>...

Set same value on multiple fields

mongodb,mongodb-query,mongodb-update
I have the following document structure: { ... timings: { mon: "", tue: "", wed: "", thu: "", fri: "", sat: "", sun: "", } ... } I want to set the value "Open 24 Hours" for all the days of the week. Currently I am using the query: db.collection.update({_id:...

Get n most recent documents based on objectId

mongodb,mongoose,mongodb-query
I am wondering if there is a way to order a result set based on the date component in an object Id myCol.find().sort('_id descending').limit(5).select('title _id').exec(function(e, data){ res.render('some-page.html',{data:data}); }); I don't have an explicit date field in my documents, but it's my understanding that objectId already contains a date component, so...

How do I write a query to get values based on two dependent input variables in MongoDB?

json,node.js,mongodb,mongodb-query,pymongo
I have a mongoDB collection that contains JSON documents in the following format. This is just a sample not the full document. { "_id": ObjectId("555ba8a6ae96b63b98969192"), "toptags": { "@attr": { "artist": "Rihanna" }, "tag": [ { "count": "100", "name": "pop", "url": "http://www.last.fm/tag/pop" }, { "count": "89", "name": "rnb", "url": "http://www.last.fm/tag/rnb" },...

mongodb bitwise check not return row

javascript,mongodb,mongodb-query
I want to bitwise check in my data, but not return data.Rights default param is 1. How do I solve this problem? db.getCollection('forms').find( { "IsActive" : true, "$or" : [ { "$where" : "(this.Acls.Rights & 1) == 1" , "Acls.Actor._id" : ObjectId("5565f392a6df191eb4689bec") }, { "$where" : "(this.Acls.Rights & 1) ==...

C# connect and query an existing MongoDb

c#,mysql,database,mongodb,mongodb-query
I'm trying to connect to my mongodb from C#. I'm not sure if I'm even actually connecting or not. Here is the connection to my mongodb: var connectionString = "mongodb://localhost:8081"; MongoClient client = new MongoClient(connectionString); var db = client.GetDatabase("nutchdatabase"); var collection = db.GetCollection<BsonDocument>("webpage"); I'm not sure on how to test...

MongoDb - Query for specific subdocument

mongodb,mongodb-query,sitecore8
I have a set of mongodb documents with the following structure: { "_id" : NUUID("58fbb893-dfe9-4f08-a761-5629d889647d"), "Identifiers" : { "IdentificationLevel" : 2, "Identifier" : "extranet\\[email protected]" }, "Personal" : { "FirstName" : "Test", "Surname" : "Test" }, "Tags" : { "Entries" : { "ContactLists" : { "Values" : { "0" : {...

mongo query - does property exist?

node.js,mongodb,mongodb-query
Within a collection document there is a 'sub' property that is an object containing 1 or more properties. The collection looks like: (I've removes extraneous other properties) "properties": { "source": { "a/name": 12837, "a/different/name": 76129 } } I need to do a find on the collection where a/name and a/different/name...

mongodb set null in update

mongodb,mongodb-query
I have to interchange the values of a document. var query = {"_id" : ObjectId("53e1c254382f891cc600076d")}; db.properties.find(query).forEach(function(prop){ printjson({"_id":prop._id, "val":prop.val, "ua":prop.ua}); db.properties.update(query, {$set:{ua: prop.val}},{$unset:{val:""}}); }); Before the update executes this prints as: { "_id" : ObjectId("53e1c254382f891cc600076d"), "val" : 9876541, "ua" : null } And after the update it turns to: { "_id"...

How to tweak the MongoDB query to get the output in descending order

mongodb-query
I am working with a OSM file converted to JSON.In this query, I am trying to fetch the count of all the amenities in the .json file.I need to know how to get the output reverse. Query :- db.char.aggregate([{"$match":{"amenity":{"$exists":1}}}, {"$group":{"_id":"$amenity", "count":{"$sum":1}}}, {"$sort":{"count":­1}}, {"$limit":100}]) Current Output:- { "_id" : "bar", "count"...

Two queries on different collections - MongoDB

mongodb,mongodb-query
I have two collections in MongoDB. The first contains information about some football coaches and the second contains data about teams. For example, this is a document of coach collection: { "_id" : ObjectId("556caaac9262ab4f14165fca"), "name" : "Luis", "surname" : "Enrique Martinez Garcia", "age" : 45, "date_Of_birth" : { "day" :...

How to query neighbor elements in MongoDB?

sql,mongodb,sorting,mongodb-query
I am implementing a ranking system. I have a collection with elements like this: {"_id" : 1, "count" : 32} {"_id" : 2, "count" : 12} {"_id" : 3, "count" : 34} {"_id" : 4, "count" : 9} {"_id" : 5, "count" : 77} {"_id" : 6, "count" : 20}...

With the mongodb-java-api, is it possible to “select” the objectID and return the value from a Mongodb.find operation in one operation?

mongodb,mongodb-query,mongodb-java
I am interested in to find the id from a single document as the result of a find operation. In Robomongo I can get the value in question with this statement: db.collection.find({ "field" : {$exists: true}}).limit(1).next()._id.valueOf() What is the minimal code in Java I have to use to get the...

MongoDB & Spring Data - Searching for a user by firstname/lastname

database,mongodb,spring-data,mongodb-query,criteria-api
I have the following collection: User { firstname, lastname } I want to search for users by firstname and/or lastname (firstname/lastname/firstname+lastname). What I have: Criteria criteria = new Criteria(); criteria.orOperator(Criteria.where("firstname").regex(searchQuery),Criteria.where("lastname").regex(searchQuery)); The problem with the above is that I can either search by firstname OR lastname, but not both (e.g. ''John...

MongoDB Can't canonicalize query: BadValue Too many text expressions

mongodb,full-text-search,mongodb-query
I am attempting to build a query for MongoDB in Java and I am running into this error, "Can't canonicalize query: BadValue Too many text expressions" whenever I run the query. The database is full of documents with a text property that is indexed for full text searching. I am...

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); ...

ERROR backtype.storm.util - Async loop died! java.lang.RuntimeException: java.lang.NullPointerException

java,mongodb,mongodb-query,storm,apache-kafka
I am trying to write the output of the Storm word count program to mongoDB.This is the error i am getting when I am executing the program.Though I am able to successfully print the reusult.Problem starts when i am trying to write the output. The error generated : Jun 01,...

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...

MongoDB return the lates record for each field

mongodb,mongodb-query
Suppose, I have this rooms collection: { room: 'room1', owner: 'user1', time: 'time1' }, { room: 'room1', owner: 'user1', time: 'time2' }, { room: 'room2', owner: 'user1', time: 'time3' }, { room: 'room2', owner: 'user1', time: 'time4' }, { room: 'room3', owner: 'user1', time: 'time5' }, { room: 'room3', owner:...

How to use fields in query evaluated criteria expressions in Mongodb?

mongodb,mongodb-query
In Mongodb, I have a tasks collection, which has following fields, along with 25 other fields 1. timeToLive - holds the number of minutes 2. createdDate - holds the ISODate I need to write a query, which will return me only unexpired tasks. I am trying something like following: db.tasks.find({"timeToLive":{$gt:((new...

MongoDB elemmatch multiple elements in array

mongodb,mongodb-query,aggregation-framework
I have an mongodb document like { "_id" : ObjectId("54e66b2da7b5f3a92e09dc6c"), "SomeMetric" : [ { //some object } { //some object } ], "FilterMetric" : [ { "min" : "0.00", "max" : "16.83", "avg" : "0.00", "class" : "s1" }, { "min" : "0.00", "max" : "16.83", "avg" : "0.00", "class"...

How to find the most recent item in a group using MongoDB aggregation framework?

mongodb,mongodb-query
I have a collection where I store messages and it looks like this: id sender receiver date ------------------------ 1 1 2 30-May-15 3:14:48 PM 2 2 1 30-May-15 3:16:28 PM 3 1 3 30-May-15 3:20:00 PM 4 1 2 30-May-15 3:21:48 PM 5 3 2 30-May-15 3:25:15 PM 6 4...

MongoDB with PHP driver - how to push onto multiple arrays with one update query?

php,mongodb,mongodb-query
I would like to push onto multiple arrays contained within the same document with a single MongoDB update query in PHP. I have tried the following two calls without success: //this one causes php run error $collection->update(array("scienceNumber"=>$scienceNumber), array('$push'=>array(array("comments"=> $comment), array("ids"=> $userID), array("times"=> $time))), array("upsert"=>true)); //this one runs a query but...

Mongodb query to select less than and equal based on custom comparator

mongodb,mongodb-query
I am using mongodb database and I need to run less than and equal filter based on custom comparator. Following is more details. "profile" collection is having "level" field as string {"name":"Test1", "level":"intermediate"} Following are value of level and its corresponding weight novice intermediate experienced advance I want to write...

Find in 2 levels of nested arrays in MongoDB

mongodb,mongodb-query
After googling a lot, I can't locate something that can handle this. And it's supposed to be simple, I guess. I've this simple json... { "_id" : ObjectId("555bd34329de3cf232434ef2"), "clients" : [ { "Client1" : { "positions" : [ { "systemId" : "xxx1", "type" : "alfa" }, { "systemId" : "xxx2",...

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 count objects inside objects

mongodb,mapreduce,mongodb-query,aggregation-framework
i want to know how many elements there are inside objects. My collections is the following: {"_id": 'xxx', "comments":{ "_id_ab6666djdkjd": { "text": "my text" }, "_id_ab6dee": { "text": "my text2" } } }, {"_id": 'xxx', "comments":{ "_id_ab6666dddjdkjd": { "text": "my text" } } } I want to count comments in...

MongoDB - is this query possibile with denormalized model?

mongodb,nosql,mongodb-query
I have this simple Mongodb document: { "_id" : ObjectId("55663d9361cfa81a5c48d54f") "name" : "Oliver", "surname" : "Queen", "age" : 25, "friends" : [ { "name" : "Jhon", "surname" : "Diggle", "age" : "30" }, { "name" : "Barry", "surname" : "Allen", "age" : "24" } ] } Is it possbile, using...

Mongodb - query for elements in a list of tags combining $all and $nin

mongodb,mongodb-query
I have a collections with records that looks something like this: { "_id" : ObjectId("55024bb1f36088d8ce7a79e8"), "date_taken" : ISODate("2015-01-13T13:50:31.000Z"), "db_filename" : "2015-01-13 13.50.31.jpg", "db_original_height" : 3264, "db_latitude" : -44.66694444444444, "db_tags" : [ "January", "2015", "Tuesday", "GT-I9300", "SAMSUNG", "New Zealand/Aotearoa", "Southland", "Afternoon", "Medium file" ], "db_original_path" : "/Users/hingem/my_image_store/imgs/2015-01-13 13.50.31.jpg", "db_date_taken" : ISODate("2015-01-13T13:50:31.000Z"),...

How do you return multiple results from a mongoDB aggregate() query?

performance,mongodb,aggregate,mongodb-query
Here is a query which runs a match, and then returns the number of unique entries in a specific field: db.sequences.aggregate([{$match: {id: 5}}, {$group : {_id : "$field"} }, {$group: {_id:1, count: {$sum : 1 }}}]) However, what if I wanted to return multiple values, such as a count of...

Mongodb: Finding and updating object property from array

mongodb,nosql,mongodb-query,mongodb-update
I have a collection with multiple documents which follow this structure: { "_id" : { "oid" : XXX }, "name" : "Name", "videos" [ { "id" : 1, "thumbnail" : "thumbnail.jpg", "name" : "Name here" }, { "id" : 2, "thumbnail" : "thumbnail.jpg", "name" : "Name here" }, { "id"...

Find Latest Object in MongoDB

mongodb,go,mongodb-query
I have data in MongoDB in the form of : { "_id" : 154, "record_id" : "001280000033x54AAA", "jsonData" : "", "user_id" : 1, "userName" : "[email protected]", "backup_no" : 1 } { "_id" : 155, "record_id" : "001280000033x54AAA", "jsonData" : "", "user_id" : 1, "userName" : "[email protected]", "backup_no" : 2 }...

MongoDB Aggregate Array with Two Fields

arrays,mongodb,mongodb-query
I have vehicles collection with the following schema, all the articles are just general products (no child products included): { "_id" : ObjectId("554995ac3d77c8320f2f1d2e"), "model" : "ILX", "year" : 2015, "make" : "Acura", "motor" : { "cylinder" : 4, "liters" : "1.5" }, "products" : [ ObjectId("554f92433d77c803836fefe3"), ... ] } And...

Mongodb Replace a word from the string

mongodb,mongodb-query
So i have a mongodb document which have a field like this Image : http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-zoom.jpg I want to replace the zoom in the string with some other text such that : Image : http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-product2.jpg Is it possible to do that??...

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...

Java MongoDB 3.0 driver query distinct without filter

java,mongodb-query
I imported Yelp Academic Dataset to MongoDB. Now I am attempting to query a list of all the unique categories from locations. In the Mongo shell, this is very simple: db.locations.distinct("categories"); In Java, it's not the same. MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase("yelp"); //this won't even compile,...

Mongo Ruby Driver #find() on Specified field Values

ruby,mongodb,mongodb-query
Ruby: ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux] RubyGem: mongo (2.0.4) I need help querying a MongoDB database with their gem and updating the appropriate fields. EDIT: I'm trying to loop over documents of a Mongo database, pull down the values of specific fields in those documents, and update them...

MongoDB explain query plan

mongodb,mongodb-query
I have a collection with index: { "authorizations.participant.participantId" : 1, "authorizations.action" : 1 } I have a query: db.users.find({ "$query" : { "$and" : [ { "authorizations" : { "$elemMatch" : { "action" : "READ" , "participant.participantId" : { "$in": ["5549b40444ae1e4a5764fb0a","5549b3f644ae1e4a5764facb"] } } } } ] }, "$explain" : true...

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....

Mongo $and query returning no results

json,mongodb,mongodb-query
How do I approach writing a query to return all the records matching both match.id and player.name for the following collection? { "match": { "id": 1, "event": { "timestamp": "2015-06-03 15:02:22", "event": "round_stats", "round": 1, "player": { "name": "Jim", "userId": 45, "uniqueId": "BOT", "team": 2 }, "shots": 0, "hits": 0,...

MongoDB combine collections or have multiple references

mongodb,mongoose,schema,mongodb-query
I have a set of categories that a user can choose from (movies, music, books, etc) and rate items within the selected category. Because each category has different parameters (movies has year, music has artist, etc) I figured split up each category into it's own collection, however, that brings up...

mongoDB: Projection of nested arrays

mongodb,mongodb-query,aggregation-framework
I've got a collection "accounts" which contains documents similar to this structure: { "email" : "[email protected]", "groups" : [ { "name" : "group1", "contacts" : [ { "localId" : "c1", "address" : "some address 1" }, { "localId" : "c2", "address" : "some address 2" }, { "localId" : "c3",...

Find and groupby

mongodb,mongodb-query,aggregation-framework
If I have the following documents in my collection { "_id" : 1, "domainName" : "test1.com", "hosting1" : "hostgator.com", "hosting2" : "hostgator.com", sID : 1} { "_id" : 2, "domainName" : "test2.com", "hosting1" : "cloud.google.com", "hosting2" : "aws.amazon.com", sID : 2} { "_id" : 3, "domainName" : "test3.com", "hosting1" :...

Meteor.users.find() - how to filter by group in alanning:roles package

meteor,mongodb-query,roles,groups
I'm trying to make an admin section on my website. The admin can go to the admin page and see a table of the users in his group. I only want to publish a the users that are in that admin's group. E.g. he is in the group ['soccer'] but...

how do i query a field in mongodb with a boolean value and return a boolean whether its true or false

javascript,mongodb,meteor,mongodb-query,boolean-logic
check my simple collection: {_id: "01", name: "Jimmy", canDrive: false } What I want to do once a document is found, is to manipulate a DOM and show a <div class="driving-tutorial> if the field canDrive value is false and hide it if the value is true like this in meteor:...

Search MongoDB Array of Objects where property has same value for more than 1 array element

arrays,mongodb,spring-data,mongodb-query,spring-mongo
I have a Mongo Collection of Products with a Categories field that is an array of objects. { "_id" : ObjectId("XXX"), "title" : "Cool Product", "details" : "Some Details", "categories" : [ { "name" : "Cat1", "isPrimary" : true }, { "isPrimary" : true, "name" : "Cat2" }, { "name"...

Removing documents from MongoDB that have same property values contained within an array

mongodb,mongodb-query
I'm struggling with trying to remove documents from MongoDB 3.0 database that share 2 property values profiles.platform and profiles.handle contained within an array. { _id: ID profiles: [{ source: {}, isProfile: Boolean, profile: {}, demographics: { male: Number, female: Number }, handle: String, platform: String }] } I tried using...

Checking nested property that can be null

mongodb,mongodb-query
I've the following data in my collection: { colour: { r: 0, g: 0, b: 0 }}, { colour: null }, How can I find all the documents that have colour == null or color.r between some values? I've tried .find({ where: { $or: [{colour: null}, {"colour.r": {$gt: 0, $lt:...

getMore executor error: Overflow sort stage buffered data usage exceeds internal limit

mongodb,mongodb-query
This is not a duplicate question. All other answers say that the solution is to create an index on the sort key. In my case, I do have an index and still face this error Given a mongodb collection with documents similar to: { '_id': ..., 'title': ..., 'price': ...,...

MongoDB upsert with empty update document

mongodb,mongodb-query
I'm trying to figure out how to insert a document into a collection iff the document is not already present in that collection. If the document is already present, the statement should be a no-op. The approach I'm taking it to use an upsert with an empty update document: db.collection.update({...

Using Dynamic strings for querying nested mongo doc

mongodb-query,node-mongodb-native
I'm using the dot notation for querying a nested mongo doc. However I want this query to be dynamically generated. For eg The nesting is as { "Car": { "Make": { "Model": "Some val" Year : "Some year" } } } If I perform a query like db.carcoll.find({'Car.Make.Model':'some val'}) I...

How to convert miliseconds to date in mongodb aggregation?

mongodb,date,aggregate-functions,mongodb-query
I have a collection in MongoDB and documents like this - [ { "campaignId": 1, "operatorId": 1, "txnType": "DR", "amount": 2, "balance": 0, "txnTime": 1428907779206, "txnSrc": "Dial_In", "msisdn": "9789877667", "circle": "Delhi", "smsContent": "Hello Mr Arif" }, { "campaignId": 1, "operatorId": 1, "txnType": "DR", "circle": "Delhi", "amount": 2, "balance": 0, "txnTime":...

Query for documents with given set of attributes in MongoDB

mongodb,mongodb-query
I'm writing a query in the mongo.exe as follows: db.sheep.find( { "timestamp" : { "$gt":ISODate("2015-05-15T10:00:00.000z"), "$lt":ISODate("2015-05-15T10:05:10.000z") } }, {"x":1,"y":1,"z":1,"timestamp":1}) However, some of the returned documents have timestamp but no x, y, z. How do I return only documents that have both timestamp and x y z? I presume there is...

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 ]...

Meteor publish-composite and nested collection

javascript,mongodb,meteor,mongodb-query
I am trying to build an app that has a many to many relationship in Meteor. There will be jobs, clients and users collections. Clients can have multiple jobs, and most importantly multiple users can work on the same job. I have the jobs collection set up as follows in...

Print a value of a mongo documents inner key

mongodb,mongodb-query
I have a document in the format: {_id:ObjectId("541...009b"), name:"abc" data:{"F_001":123abc, "priority":"urgent", ...},... } Wanted to write a common function to update a key {data.F_001:0}, otherwise all data will remain as it is: updateExistingKey("user", {name:"abc"}, "data.F_001"); As I wasn't able to achieve that goal, I've tried to print the value, without...

Mongodb Query for finding distance between latitude and longitude points

mongodb,mongoose,geolocation,geocoding,mongodb-query
I have a user's collection with Latitude and longitude points for each user. I want to calculate distance between given Lat, long values and user's location. In MYSQL there is a query for it SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) *...

Get result from mongo aggregation using pymongo 3.0

python,mongodb,mongodb-query,aggregation
I know it may be a very simple question but I cant figure it out, im getting the same error again and again: I amb using python to query a mongo collection and retrive a value from it, here it is: subquery = db.partsupp.aggregate([ {"$match": {"r_name": region }}, {"$group": {...

convert miliseconds to date in mongodb aggregation pipeline for group by?

mongodb,mongodb-query
I have to convert milliseconds to date format in mongodb aggregation pipiline - My query is - db.campaign_wallet.aggregate({"$match" : {"campaignId" : 1, "txnTime" : { "$gte" : 1429554600000, "$lte" : 1430159400000}}}, {"$group" : {"_id" : {"msisdn" : "$msisdn", "txnTime" : "$txnTime"}, "count" : {"$sum": 1}}}); In this query how to...

mongodb query using $in for list of lists

mongodb,mongodb-query
I have a document as: { 'name':'XYZ', 'address':'Street 21', 'phone': { 'home': [123456, 456123] }, 'qualification': { 'primary': [ ['AB','75'], ['CD','80'], ['EF','50'] ] } } Simple query would be like: n = collection.find({'name':'XYZ'}) I can fetch documents using a list on the 'phone.home' subdocument key like this: list1 = [123456]...

How to update a subdocument in mongodb

mongodb,mongodb-query
I know the question have been asked many times, but I can't figure out how to update a subdocument in mongo. Here's my Schema: // Schemas var ContactSchema = new mongoose.Schema({ first: String, last: String, mobile: String, home: String, office: String, email: String, company: String, description: String, keywords: [] });...

get the fields in the input document after $group in aggregation pipeline in MongoDB

mongodb,mongodb-query,aggregation-framework
The problem I am facing is that how to access the original document after one group operation and also carry the fields after $group in aggregation pipeline in MongoDB. For example: [ group, unwind, group] Original document is: { "_id" : ObjectId("361de42f1938e89b179dda42"), "user_id" : ObjectId("9424021bafbde55512e39b83"), "candidate_id" : ObjectId("54f65356294160421ead3ca1") "OVERALL_SCORE" :...

MongoDB aggregate - match using lte and fallback to gte

mongodb,mongodb-query
I have a MongoDB collection with a structure (simplified) like this: [ { "name" : "name1", "instances" : [ { "value" : 1, "score" : 2, "date" : ISODate("2015-03-04T00:00:00.000Z") }, { "value" : 2, "score" : 5, "date" : ISODate("2015-04-01T00:00:00.000Z") }, { "value" : 2.5, "score" : 9, "date" :...

How to retrieve a value from mongoDB?

java,mongodb,mongodb-query,mongo-java,mongo-java-driver
I am new to mongoDB and using java with mongoDB. I have a json where I want to retrieve the column names and not the value.I also need to store it in two different array. Desired output is: column [ ] = views, AddToCart, AddToWishList, ZoomedProductImage list [ ] =...

Query by comparing pieces within a document

mongodb,mongodb-query
The documents i'm querying on have two sub parts called OldResults and NewResults. What i want to do is to find all documents where OldResults != NewResults. Is such a query possible in Mongo? Please be aware that the schema of OldResults & NewResults could be different for different documents...

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...

MongoDb shell simple find(): Why not authorized?

mongodb,mongodb-query,mongodb-shell
How is this even possible? What am I missing?... Edit 1: Ignore the db.posts.find vs. db.post.find typo above. I re-auth'd and tried the latter and get exact same denial. Am I dumb or do MongoDb permissions make no sense at all? Ok don't answer that first part ;-) Thanks a...

CURDATE() function like in mysql for mongoDB

javascript,mongodb,mongodb-query
Have seen that new Date() will display the current date with time. But I need only date part. new Date() ISODate("2015-06-11T06:49:17.684Z") I need only date part--> ISODate("2015-06-11T00:00:00.000Z") Below is the sample data: { "_id": ObjectId("55743942789a9abe7f4af40e"), "msisdn": "9xxxxxxxxx", "act_date": ISODate("2014-09-16T00:00:00Z"), "date": ISODate("2015-06-07T00:00:00Z"), "recharge": { "recharge_amt": 100, "rechargetype": "WEB" }, "voice": {...

mixing $in and $or mongo search operations

mongodb,mongodb-query
Folks, I am trying to mix $all and $nin mongodb 2.6 query parameters. Is mixing $or with $all and $nin allowed in such manner? Essentially what we are trying to retrieve here, are documents that either have ['foo','bar']... OR that dont have ['baz'] query: { "_type": { "$in": [ "A"...

MongoDB cannot project string value from _id

node.js,mongodb,mongodb-query
I have an aggregate to pull metrics from a collection of "share" actions. These metrics are grouped by day and the platform(twitter, pintrest, etc). Each stage works fine except when it comes to formatting the output in a $project stage, I cannot seem to get the platform string to project...

Mongo: get hashmap in aggregate

javascript,mongodb,hashmap,aggregate,mongodb-query
I have collection db.problems. Each document contains nested area and category objects. Document's example: { _id: 1, text: 'Hello', area: {_id: 23, title: 'Area 61'}, category: {_id: 12, title: 'Just a category'} } I'm trying to count problems in every area by category and get something like this: [ {...

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...

What package do I need to import for the Jackson mongodb DBquery functions to compile in Java?

java,mongodb,mongodb-query,mongodb-java,mongo-jackson-mapper
I have this query string : coll.find(and(DBQuery.greaterThanEquals("createdOn", startDate), DBQuery.lessThanEquals("createdOn", endDate),DBQuery.is("user_email",userEmail))); I am getting the error : cannot find symbol [symbol: variable DBQuery] [location: class models.food.UserMeal] Now a plain DB query coll.find(); is working smoothly. What package am I missing for this to work? Update : I tried importing : import...

How do i count number of referals using aggregation in mongoDB

mongodb,mongodb-query,aggregation-framework
this is the schema : { "_id" : ObjectId("54f8d7ad92ccf803008a0e4f"), "personal" : { "name" : "test", "placa" : "BBB222" }, "recruiter" : { "user_id" : "541cba6fe4b0288d56081fe2", "date" : 1425594285410, "name" : "Mario Hart", "rol" : "greeter", "channel" : "referido", "referred" : "VERA" }, I want to create a list of names...

How to add a new array field to collection in mongodb?

mongodb,mongoose,mongodb-query
For example, I have a collection, such as User, with one field name (and default _id field). I insert some documents to this collection. Then I want to add a field emails (which is an array to insert multiple emails) to this collection. If it is a normal field (not...

MongoDB aggregate result with two different keys

arrays,mongodb,mongodb-query
I have recently put this question that helped me to obtain an array for obtaining a result in an aggregation mongoDB query ( MongoDB Aggregate Array with Two Fields ) My problem right now is to obtain combine two different keys. I have a products collection with general products on...

MongoDB: Project using array fields

mongodb,mongodb-query,aggregation-framework
I have a collection like this: Each document contains Message field which in turn contains array of Fields. Each document underneath Fields array has Value and Name properties. [ { "_id" : ObjectId("55711efed0103b1598140076"), "Message" : { "Fields" : [ { "Value" : 131, "Name" : "Options", }, { "Value" :...

Deleting documents from MonogDB

mongodb,mongodb-query,deletion
I have users' collection from which I want to delete the documents which have only 2 fields. My general schema is like this: { _id: 1, name: af, city: asd, transaction: 1, transactions:[{ id:1, product: mobile, amount: 10 }, id:2, product: tv, amount: 23 }], many-other-sub-docs:[], } I want to...

How to select where sum of fields is greater than a value in MongoDB

mongodb,nosql,mongodb-query,nosql-aggregation
Using MongoDB, How would I write this regular SQL statement? SELECT * FROM table WHERE (field1+field2+field3) > 1 I've been messing with $group, $project, $add, etc. I feel like I'm dancing all around the solution but can't figure it out....

Difference between Find and FindAsync

c#,mongodb,mongodb-query,mongodb-csharp-2.0
I am writing a very, very simple query which just gets a document from a collection according to its unique Id. After some frusteration (I am new to mongo and the async / await programming model), I figured this out: IMongoCollection<TModel> collection = // ... FindOptions<TModel> options = new FindOptions<TModel>...

Average of value fields of documents with id higher than 10

node.js,mongodb,mongodb-query,aggregation-framework
I'm using express, nodejs, monk. collection consists of objects: {_id, valueField} Let's assume that _id is overridden on insert and the id's of 5 documents in the collection range from 1 to 5. They are all integers. This is what I'm trying now - but I believe the syntax is...

Text query through referenced objects with MongoDB

mongodb,mongodb-query
I have the following structure. books collection: { _id: "book_1", title: "How to build a house", authorId: "author_1" } { _id: "book_2", title: "How to plant a tree", authorId: "author_2" } authors collection: { _id: "author_1", name: "Adam Adamson" } { _id: "author_2", name: "Brent Brentson" } I want to...

MongoDB: How to find a document by an id inside a nested document

mongodb,mongodb-query,embedded-documents
Given a collection like this:.. [ { "_id" : ObjectId("5546329a470000850084a621"), "name": "Joe", "surname": "Smith", "accounts": [ { "_id" : ObjectId("5546329a470000850084a655"), "default": true, "status" : "approved", "activationTime" : ISODate("2013-05-03T14:37:15.025Z") }, { "_id" : ObjectId("5546329a470000850084a688"), "default": true, "status" : "approved", "activationTime" : ISODate("2014-06-03T14:37:15.025Z") } ] }, { "_id" : ObjectId("9546329a470079850084a622"), "name": "Jimmy",...

MongoDb aggregation-framework, join different documents are in the same collection

mongodb,mongodb-query,aggregation-framework
I want to help get mongodb one of several documents. I have the following data structure: db.coll.insert([ {_id: "gomer", doc_type: "user", group: ["user", "author"] }, {_id: "dante", doc_type: "user", group: ["user"] }, {_id: 1, doc_type: "blogs", user: "gomer", article: "aaaa" }, {_id: 2, doc_type: "blogs", user: "vasya", article: "bbbb" }...

Remove mongodb document fields

mongodb,mongodb-query
I am wanting to update my document structure wherein I wish to remove particular fields based on value. "id" : "company", "keys" : { "0" : { "key_name" : "Name", "section_head" : "Profile" }, "1" : { "key_name" : "Sector", "section_head" : "Profile" }, "2" : { "key_name" : "SubSector",...

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":...

iterating over a Mongo Cursor with finite batch size

mongodb,cursor,mongodb-query
How can I iterate over the following data cursor? Following code gives error " TypeError: Object [object Object] has no method 'forEach' var data = db.profiles.runCommand("aggregate", { pipeline: [ {$limit: 100000}, {$unwind: "$Items"}, { $group: { _id: "$Items", count: {$sum: 1} }, }, ], allowDiskUse: true, cursor: { batchSize: 100...

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"...

Model.aggregate gives me different results as in the mongo console (none for mongoose)

node.js,mongodb,mongoose,mongodb-query,aggregation-framework
When I execute the following in the console I get one nameID and a min max. db.prices.aggregate([ {"$match":{ nameID: { '$in': [ ObjectId('longid') ] } } }//replaced the actual value with longid ,{"$group":{"_id":"$nameID","nameID":{"$first": "$nameID"} ,"min":{"$min":"$price"},"max":{"$max":"$price"}}} ,{"$sort":{"min":1}} ,{"$limit":5} ]) When in mongoose I get an empty array: Price.aggregate([ {"$match":{ nameID: {...

Need help in mongoDB aggregate Query

mongodb,mongodb-query
I need max date for SUCCESS status for each mid .Below is the document structure. I tried using aggregate but unble to get the required result. {"mid":1,"date":ISODate("2015-06-07T00:00:00Z"),"status":"FAILED"} {"mid":1,"date":ISODate("2015-06-04T00:00:00Z"),"status":"FAILED"} {"mid":1,"date":ISODate("2015-06-01T00:00:00Z"),"status":"SUCCESS"} {"mid":1,"date":ISODate("2015-05-27T00:00:00Z"),"status":"SUCCESS"} {"mid":2,"date":ISODate("2015-05-17T00:00:00Z"),"status":"SUCCESS"}...

Search Exact Array Values In Multiple Fields

arrays,mongodb,mongodb-query,aggregation-framework
I have a collection which has 3 documents like below: Collection: { name: "A", arr: [1, 2, 3], arr1: [4, 5, 6] }, { name: "B", arr: [3, 7, 11], arr1: [5, 6, 9] }, { name: "C", arr: [3, 4, 5], arr1: [7, 9, 12] } I want to...

Is it possible to migrate data from MongoDB to SQL-Server? [closed]

sql,sql-server,database,mongodb,mongodb-query
I searched around I found that there are ways to transfer/sync data from sql-server to mongodb. I also know that Mongodb contains collections instead of table and the data is stored differently. I want to know if it is possible to move data from mongodb to sql-server? If yes then...

Sum unique properties in different collection elements

mongodb,mongodb-query
I am quite new to MongoDB. Hopefully I am using the correct terminology to express my problem. I have the following collection: Data collection { "name":"ABC", "resourceId":"i-1234", "volumeId":"v-1234", "data":"11/6/2013 12AM", "cost": 0.5 }, { "name":"ABC", "resourceId":"v-1234", "volumeId":"", "data":"11/6/2013 2AM", "cost": 1.5 } I want to query the collection such that...

MongoDB C# 2.0 Driver Multiple Unwinds

c#,mongodb,aggregate,mongodb-query
I'm trying out Mongo for the first time and am having an issue where I have: public class A { public int ID {get;set;} . . . public List<B> Bs { get; set; } } public class B { public int ID { get; set; } . . . public...

MongoDB .Net driver 2.0 Builders Filter (field to array comparison)

mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0
I need to get all usernames from "followingList.username" and compare with posts' usernames, if there any match need to add that one to an array. Person Model { "_id" : ObjectId("554f20f5c90d3c7ed42303e1"), "username" : "fatihyildizhan", "followingList" : [ { "_id" : ObjectId("55505b6ca515860cbcf7901d"), "username" : "gumusluk", "avatar" : "avatar.png" }, { "_id"...