Skip to main content

Questions tagged [mongodb-query]

This tag is for questions related to querying and updating MongoDB collections, either through the mongo shell or using a programming language driver.

mongodb-query
Filter by
Sorted by
Tagged with
1949 votes
47 answers
1.8m views

How to query MongoDB with "like"

I want to query something with SQL's like query: SELECT * FROM users WHERE name LIKE '%m%' How can I achieve the same in MongoDB? I can't find an operator for like in the documentation.
Freewind's user avatar
  • 197k
978 votes
16 answers
792k views

Query for documents where array size is greater than 1

I have a MongoDB collection with documents in the following format: { "_id" : ObjectId("4e8ae86d08101908e1000001"), "name" : ["Name"], "zipcode" : ["2223"] } { "_id" : ObjectId("...
emson's user avatar
  • 10.4k
561 votes
17 answers
1.1m views

Find objects between two dates MongoDB

I've been playing around storing tweets inside mongodb, each object looks like this: { "_id" : ObjectId("4c02c58de500fe1be1000005"), "contributors" : null, "text" : "Hello world", "user" : { "...
Tom's user avatar
  • 34.1k
546 votes
12 answers
399k views

Update MongoDB field using value of another field

In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like: UPDATE Person SET Name = FirstName + ' ' + LastName And the ...
Chris Fulstow's user avatar
487 votes
18 answers
486k views

How to remove a field completely from a MongoDB document?

{ name: 'book', tags: { words: ['abc','123'], lat: 33, long: 22 } } Suppose this is a document. How do I remove "words" completely from all the documents in this ...
TIMEX's user avatar
  • 268k
485 votes
20 answers
492k views

Retrieve only the queried element in an object array in MongoDB collection

Suppose you have the following documents in my collection: { "_id":ObjectId("562e7c594c12942f08fe4192"), "shapes":[ { "shape":"square", "color":"blue" }, ...
Sebtm's user avatar
  • 7,122
448 votes
30 answers
230k views

How can I get a random record from MongoDB?

I am looking to get a random record from a huge collection (100 million records). What is the fastest and most efficient way to do so? The data is already there and there are no field in which I can ...
Will M's user avatar
  • 4,481
350 votes
8 answers
531k views

How to list all databases in the mongo shell?

I know how to list all collections in a particular database, but how do I list all available databases in MongoDB shell?
fracz's user avatar
  • 21.1k
344 votes
12 answers
643k views

MongoDB - return query based on date

I have a data like this in mongodb { "latitude" : "", "longitude" : "", "course" : "", "battery" : "0", "imei" : "0", "altitude" : "F:3.82V", "mcc" : "07", "...
coure2011's user avatar
  • 41.7k
315 votes
11 answers
488k views

MongoDB: Combine data from multiple collections into one..how?

How can I (in MongoDB) combine data from multiple collections into one collection? Can I use map-reduce and if so then how? I would greatly appreciate some example as I am a novice.
user697697's user avatar
  • 3,387
305 votes
4 answers
301k views

How to query nested objects?

I have a problem when querying mongoDB with nested objects notation: db.messages.find( { headers : { From: "[email protected]" } } ).count() 0 db.messages.find( { 'headers.From': "...
Edmondo's user avatar
  • 19.9k
247 votes
17 answers
195k views

How to Update Multiple Array Elements in mongodb

I have a Mongo document which holds an array of elements. I'd like to reset the .handled attribute of all objects in the array where .profile = XX. The document is in the following form: { "...
LiorH's user avatar
  • 18.7k
196 votes
10 answers
283k views

mongodb: insert if not exists

Every day, I receive a stock of documents (an update). What I want to do is insert each item that does not already exist. I also want to keep track of the first time I inserted them, and the last ...
LeMiz's user avatar
  • 5,594
182 votes
6 answers
133k views

Include all existing fields and add new fields to document

I would like to define a $project aggregation stage where I can instruct it to add a new field and include all existing fields, without having to list all the existing fields. My document looks like ...
samuelluis's user avatar
  • 1,821
180 votes
8 answers
137k views

MongoDB vs Firebase [closed]

MongoDB vs Firebase What are some quantitative advantages of using Firebase over MongoDB? (not opinions) I know that Firebase is a cloud-based service with its own API, but I feel like Mongo may give ...
itsclarke's user avatar
  • 8,852
173 votes
10 answers
290k views

mongodb count num of distinct values per field/key

Is there a query for calculating how many distinct values a field contains in DB. f.e I have a field for country and there are 8 types of country values (spain, england, france, etc...) If someone ...
Liatz's user avatar
  • 5,147
158 votes
10 answers
223k views

MongoDB: How to query for records where field is null or not set?

I have an Email document which has a sent_at date field: { 'sent_at': Date( 1336776254000 ) } If this Email has not been sent, the sent_at field is either null, or non-existant. I need to get the ...
Andrew's user avatar
  • 235k
152 votes
8 answers
213k views

$lookup on ObjectId's in an array

What's the syntax for doing a $lookup on a field that is an array of ObjectIds rather than just a single ObjectId? Example Order Document: { _id: ObjectId("..."), products: [ ObjectId("..<...
Jason Lin's user avatar
  • 1,997
143 votes
10 answers
220k views

Get the latest record from mongodb collection

I want to know the most recent record in a collection. How to do that? Note: I know the following command line queries works: 1. db.test.find().sort({"idate":-1}).limit(1).forEach(printjson); 2. db....
inkriti's user avatar
  • 1,665
137 votes
3 answers
256k views

How to filter array in subdocument with MongoDB [duplicate]

I have array in subdocument like this { "_id" : ObjectId("512e28984815cbfcb21646a7"), "list" : [ { "a" : 1 }, { "a" : 2 }, { ...
chenka's user avatar
  • 1,473
126 votes
2 answers
121k views

How can I use 'Not Like' operator in MongoDB

I can use the SQL Like Operator using pymongo, db.test.find({'c':{'$regex':'ttt'}}) But how can I use Not Like Operator? I tried db.test.find({'c':{'$not':{'$regex':'ttt'}}) but got error: ...
KyungHoon Kim's user avatar
123 votes
11 answers
37k views

Does MongoDB's $in clause guarantee order

When using MongoDB's $in clause, does the order of the returned documents always correspond to the order of the array argument?
user2066880's user avatar
  • 4,974
120 votes
5 answers
63k views

How to execute update ($set) queries in MongoDB Compass tool?

I'm new to MongoDB Compass tool and am trying to update a field in my collection. Please can someone suggest where the update query must be written. Could find no options or panes in the tool to write ...
Patrick's user avatar
  • 1,755
117 votes
5 answers
98k views

Searching by ObjectId on Mongo Compass

How does one use Mongo Compass and search by ObjectID? I've been searching for the documentation for this but haven't been successful with anything. I have tried: { "_id" : "...
aamirl's user avatar
  • 1,470
111 votes
5 answers
199k views

How to join multiple collections with $lookup in mongodb

I want to join more than two collections in MongoDB using the aggregate $lookup. Is it possible to join? Give me some examples. Here I have three collections: users: { "_id" : ObjectId("...
Siva M's user avatar
  • 1,149
109 votes
8 answers
174k views

Printing Mongo query output to a file while in the mongo shell

2 days old with Mongo and I have a SQL background so bear with me. As with mysql, it is very convenient to be in the MySQL command line and output the results of a query to a file on the machine. I am ...
Parijat Kalia's user avatar
108 votes
8 answers
155k views

Redirect output of mongo query to a csv file

I am using MongoDB 2.2.2 for 32-bit Windows7 machine. I have a complex aggregation query in a .js file. I need to execute this file on the shell and direct the output to a CSV file. I ensure that the ...
Aafreen Sheikh's user avatar
108 votes
3 answers
112k views

Return only matched sub-document elements within a nested array

The main collection is retailer, which contains an array for stores. Each store contains an array of offers (you can buy in this store). This offers array has an array of sizes. (See example below) ...
Vico's user avatar
  • 1,309
103 votes
8 answers
203k views

How to convert a pymongo.cursor.Cursor into a dict?

I am using pymongo to query for all items in a region (actually it is to query for all venues in a region on a map). I used db.command(SON()) before to search in a spherical region, which can return ...
gladys0313's user avatar
  • 2,639
101 votes
11 answers
123k views

MongoDB Full and Partial Text Search

Env: MongoDB (3.2.0) with Mongoose Collection: users Text Index creation: BasicDBObject keys = new BasicDBObject(); keys.put("name","text"); BasicDBObject options = new ...
Leonel's user avatar
  • 2,836
95 votes
6 answers
65k views

How to use MongoDBs aggregate `$lookup` as `findOne()`

So as you all know, find() returns an array of results, with findOne() returning just a simply object. With Angular, this makes a huge difference. Instead of going {{myresult[0].name}}, I can simply ...
Fizzix's user avatar
  • 24.2k
92 votes
8 answers
220k views

MongoDB "root" user

Is there a super UNIX like "root" user for MongoDB? I've been looking at http://docs.mongodb.org/manual/reference/user-privileges/ and have tried many combinations, but they all seem to lack in an ...
No_name's user avatar
  • 2,760
89 votes
1 answer
225k views

Mongodb find() query : return only unique values (no duplicates) [duplicate]

I have a collection of documents : { "networkID": "myNetwork1", "pointID": "point001", "param": "param1" } { "networkID": "myNetwork2", "pointID": "point002", "param": "param2"...
Franckl's user avatar
  • 1,461
89 votes
3 answers
80k views

What's the difference between replaceOne() and updateOne() in MongoDB?

MongoDB bulk operations have two options: Bulk.find.updateOne() Adds a single document update operation to a bulk operations list. The operation can either replace an existing document or update ...
Mike's user avatar
  • 14.4k
88 votes
10 answers
120k views

How to exclude one particular field from a collection in Mongoose?

I have a NodeJS application with Mongoose ODM(Mongoose 3.3.1). I want to retrieve all fields except 1 from my collection.For Example: I have a collection Product Which have 6 fields,I want to select ...
dany's user avatar
  • 1,861
88 votes
6 answers
84k views

Conditional grouping with $exists inside $cond

I have two keys A and B and their existence in the document is mutually exclusive. I have to group by A when A exists and group by B when B exists. So I am $projecting the required value into a ...
Aafreen Sheikh's user avatar
88 votes
6 answers
97k views

Overflow sort stage buffered data usage exceeds internal limit

Using the code: all_reviews = db_handle.find().sort('reviewDate', pymongo.ASCENDING) print all_reviews.count() print all_reviews[0] print all_reviews[2000000] The count prints 2043484, and it ...
sheetal_158's user avatar
  • 7,791
84 votes
18 answers
92k views

Get a count of total documents with MongoDB when using limit

I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. ...
randombits's user avatar
83 votes
3 answers
137k views

How to get all the values that contains part of a string using mongoose find?

I have the following problem retrieving data from MongoDB using mongoose. Here is my Schema: const BookSchema = new Schema( { _id:Number, title:String, authors:[String], ...
Dyan's user avatar
  • 1,743
81 votes
3 answers
66k views

MongoDB C# Driver - Ignore fields on binding

When using a FindOne() using MongoDB and C#, is there a way to ignore fields not found in the object? EG, example model. public class UserModel { public ObjectId id { get; set; } public ...
LiamB's user avatar
  • 18.5k
81 votes
2 answers
88k views

MongoDB nested lookup with 3 levels

I need to retrieve the entire single object hierarchy from the database as a JSON. Actually, the proposal about any other solution to achieve this result would be highly appreciated. I decided to use ...
Yuriy's user avatar
  • 1,394
79 votes
3 answers
40k views

MongoDB - The argument to $size must be an Array, but was of type: EOO / missing

Trying to create a MongoDB data source with icCube. The idea is to return the size of an array as a new field. Something like : $project: { "people": 1, "Count myFieldArray" : {$size : "$...
ic3's user avatar
  • 7,580
79 votes
11 answers
91k views

MongoDB - Query on the last element of an array?

I know that MongoDB supports the syntax find{array.0.field:"value"}, but I specifically want to do this for the last element in the array, which means I don't know the index. Is there some kind of ...
Joseph Blair's user avatar
  • 1,415
78 votes
6 answers
91k views

How to stop insertion of Duplicate documents in a mongodb collection

Let us have a MongoDB collection which has three docs.. db.collection.find() { _id:'...', user: 'A', title: 'Physics', Bank: 'Bank_A' } { _id:'...', user: 'A', title: 'Chemistry', Bank: 'Bank_B' ...
shashank's user avatar
  • 977
76 votes
5 answers
66k views

Update field in exact element array in MongoDB

I have a document structured like this: { _id:"43434", heroes : [ { nickname : "test", items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }, ] } Can I $...
Denis Ermolin's user avatar
75 votes
3 answers
115k views

Is there an "upsert" option in the mongodb insert command?

I know this may be a silly question, but I read on an e-book that there is an upsert option in MongoDB insert. I couldn't find proper documentation about this. Can someone educate me about this?
astroanu's user avatar
  • 3,976
75 votes
1 answer
22k views

MongoDB Find performance: single compound index VS two single field indexes

I'm looking for an advice about which indexing strategy to use in MongoDb 3.4. Let's suppose we have a people collection of documents with the following shape: { _id: 10, name: "Bob", ...
Enrico Massone's user avatar
74 votes
4 answers
86k views

List all values of a certain field in mongodb

How would I get an array containing all values of a certain field for all of my documents in a collection? db.collection: { "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 } { "_id" : ObjectId(...
chimpsarehungry's user avatar
73 votes
4 answers
85k views

Mongodb Join on _id field from String to ObjectId

I have two collections User { "_id" : ObjectId("584aac38686860d502929b8b"), "name" : "John" } Role { "_id" : ObjectId("584aaca6686860d502929b8d"), "role" : "Admin", "userId" : "...
Kavya Mugali's user avatar
  • 1,088
73 votes
3 answers
90k views

Conditional $sum in MongoDB

My collection in mongodb is similar to the following table in SQL: Sentiments(Company,Sentiment) Now, I need to execute a query like this: SELECT Company, SUM(CASE WHEN Sentiment >0 THEN ...
Aafreen Sheikh's user avatar

1
2 3 4 5
350