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.
17,478
questions
1934
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.
971
votes
16
answers
775k
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("...
558
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" : {
"...
544
votes
12
answers
392k
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 ...
485
votes
20
answers
489k
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"
},
...
477
votes
18
answers
473k
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 ...
445
votes
30
answers
227k
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 ...
345
votes
8
answers
514k
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?
340
votes
12
answers
625k
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",
"...
315
votes
11
answers
481k
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.
301
votes
4
answers
296k
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': "...
247
votes
16
answers
194k
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:
{
"...
194
votes
10
answers
280k
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 ...
180
votes
6
answers
130k
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 ...
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 ...
172
votes
10
answers
285k
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 ...
155
votes
9
answers
217k
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 ...
151
votes
8
answers
210k
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("..<...
143
votes
10
answers
217k
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....
137
votes
3
answers
253k
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
},
{
...
124
votes
2
answers
118k
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:
...
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?
118
votes
5
answers
59k
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 ...
116
votes
5
answers
94k
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" : "...
111
votes
5
answers
197k
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("...
107
votes
8
answers
153k
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 ...
107
votes
8
answers
170k
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 ...
107
votes
3
answers
111k
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)
...
102
votes
8
answers
199k
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 ...
101
votes
11
answers
121k
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 ...
94
votes
6
answers
64k
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 ...
92
votes
8
answers
216k
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 ...
88
votes
10
answers
117k
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 ...
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 ...
87
votes
1
answer
221k
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"...
87
votes
3
answers
79k
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 ...
86
votes
6
answers
82k
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 ...
84
votes
18
answers
90k
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. ...
83
votes
3
answers
135k
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],
...
81
votes
2
answers
86k
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 ...
79
votes
3
answers
65k
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 ...
79
votes
3
answers
39k
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 : "$...
79
votes
11
answers
90k
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 ...
78
votes
6
answers
90k
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' ...
76
votes
5
answers
65k
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 $...
75
votes
3
answers
114k
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?
75
votes
1
answer
21k
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",
...
73
votes
4
answers
84k
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(...
72
votes
4
answers
84k
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" : "...
72
votes
4
answers
71k
views
Is it possible to flatten MongoDB result query?
I have a deeply nested collection in my MongoDB collection.
When I run the following query:
db.countries.findOne({},{'data.country.neighbor.name':1,'_id':0})
I end up with this nested result here:
...