17,494 questions
0
votes
1
answer
40
views
In a MongoDB transaction, are index entries updated immediately when an indexed field is modified?
I'm working with MongoDB transactions (Node.js, replica set). Inside a transaction, I update a document in a way that changes the value of a field that is covered by an index. Later in the same ...
Best practices
0
votes
1
replies
57
views
Mongodb Using aggregates for advanced search
Trying to solve a conundrum I have in writing some queries.
I’ve traditionally used simple find operations (and cursor operations for paging functionalities), but need something more complex to ...
3
votes
1
answer
58
views
Query not printed as expected
exports.getAllProducts = async (req, res) => {
try {
console.log(req.query);
const queryObj = { ...req.query };
const excludedFilters = ["page", "limit", "...
0
votes
1
answer
53
views
Mongo unexpected mongo queries
i have some problems in production using mongo
We have python using mongo and mongo-express for ui. And we are facing performance issues, after research i found db.currentOp() to see queries which are ...
1
vote
0
answers
47
views
Watching for changes on an array of a document in a Mongo collection only triggers on the second push, not the first
Say I have a document in a Mongo collection that looks like the following:
{
"_id": "01:550204",
"somefield1": "someValue1",
"somefield2": "...
-2
votes
1
answer
95
views
In MongoDB, is there a performance difference between $in covering all possible values vs leaving the field out in a compound index?
I’m working with a MongoDB compound index like this:
db.users.createIndex({ gender: 1, city: 1, age: 1 })
Suppose city has only a few possible values, e.g., "Chicago", "LA", "...
-3
votes
1
answer
97
views
query that tries to match everything does not use the index [closed]
https://mongoplayground.net/p/2CHyeuaG0y0
db.test.aggregate([
{
$match: {
$or: [
{
cheese: {
"$exists": true
}
},
{
...
0
votes
1
answer
85
views
All fields except _id disappeared from a MongoDB document after a $set operation
I'm using MongoDB Atlas 7.0 on a dedicated cluster and encountered a bizarre issue where a document in one of my collections mysteriously lost all its fields except for the _id.
I performed a ...
0
votes
1
answer
91
views
Does MongoDB update an index when array elements are only reordered?
I’m working with a collection where documents contain an array of subdocuments, for example:
{
"_id": 1,
"tasks": [
{ "priority": 2, "dueDate": "...
-1
votes
1
answer
71
views
Can MongoDB use a compound index to sort when filtering with $in?
I have a users collection with a compound index:
db.users.createIndex({
bin: 1,
gender: 1,
age: 1,
location: 1,
// ... other fields
});
When I query like this:
db.users.find({
bin: X,
...
0
votes
1
answer
55
views
Performance impact of updating leading vs. trailing fields in a MongoDB compound index
I am working with MongoDB and have a compound index on a collection, e.g., { a: 1, b: 1 }. I want to understand the performance implications when updating documents with respect to the fields in this ...
2
votes
0
answers
137
views
MongoDB Atlas connection error: queryTxt ETIMEOUT with Mongoose
Mongoose connection to MongoDB Atlas fails with queryTxt ETIMEOUT
I’m trying to connect my Node.js app to MongoDB Atlas using Mongoose, but the connection fails with a timeout error.
Here’s the error ...
-2
votes
1
answer
83
views
can mongoDB use the full depth of a compound index on an array of subdocuments?
index:
{
"name": "tar",
"key": {
"tar.a": 1,
"tar.b": 1
}
tar is an array of subdocuments.
query:
...
-5
votes
1
answer
78
views
Can MongoDB use an index for $exists: false on an indexed field? [closed]
Given a aggregation pipeline like this, in which I use a $match with { $exists: false } on a indexed field:
db.collection.aggregate([
{
$match: {
myField: { $exists: false }
}
}
])
...
2
votes
1
answer
154
views
MongoDB Compass connects to secondary node instead of primary in Replicasets
I have a MongoDB replica set deployed in a Kubernetes cluster using the MongoDB Kubernetes Operator. I can connect to the database using mongosh from within the cluster, but when I try to connect ...
0
votes
1
answer
103
views
Using Mongodb Project() on ColdFusion
I want to do this in ColdFusion
RecurringType = rc.db.RecurringType
.find()
.sort({ "SortOrder" : 1 })
.project({_id : 0})
.toArray();
However I get an error message of
...
0
votes
1
answer
67
views
Why is a required field (userId) undefined in Mongoose even though it exists in the database?
I'm using Mongoose with a MongoDB collection where the userId field is defined as required in my schema like this -
userId: {
type: String,
required: true,
ref: 'user'
}
When I fetch document ...
0
votes
1
answer
60
views
Mongo how to group by and count all values which is in list of dicts
How to group by and count value of field which is in list?
I have documents looks like this:
[
{"_id": "some_id","uuid": "unique_uuid", "my_field": [{&...
1
vote
1
answer
44
views
Update multiple nested parameters at once without writing the full route at each
I have the following object in MongoDB.
{
_id: "9839021321",
forms: [
{
formName: "sample_form_name",
version: [
{
version: "1",
...
2
votes
1
answer
88
views
Atomicity in mongoDB updateOne
db.collection.updateOne(
{ _id: "unique_object_id", field_a: 5 },
{ $inc: { field_a: 1 } }
)
Let's suppose that in the collection, only one document has field_a equaling 5, ie, only ...
3
votes
1
answer
104
views
MongoDB - Document query with the field value dynamically (Condition with dynamic date)
const orders = await db1.db.collection("order_all").find({
progress_status_kd: { $in: [32, 33] },
ps_screen_preparing_n_packaging_permission: true,
$expr: {
$lte: [
...
0
votes
2
answers
60
views
auth mechnism failing in mongodb
while starting from mongod.conf using below entry mongod not running throwing error:
mongod.service : main process exited, code=exited, status=2/INVALIDARGUMENT
IN MONGD.CONF: when commenting ...
0
votes
1
answer
50
views
MongoDB Java Driver returns all documents instead of matching filter in Java Servlet
I'm building an Expense Tracker web app using Java Servlets and MongoDB. I want to filter expense documents based on user and category (e.g., user: "chir", category: "education").
...
0
votes
1
answer
88
views
"Query Targeting: Scanned Objects / Returned" Exceeding 1000 – How to Fix?
I'm using MongoDB Atlas and noticed a warning in the Performance Advisor and monitoring dashboard:
"Query Targeting: Scanned Objects / Returned" has gone above 1000
From my understanding, ...
0
votes
1
answer
68
views
what is the maximum number of elements an array used in $nin should have?
The user collection in my MongoDB database needs to be searched to find content for my users. Each user has their list of blocked users.
const suggested_content = await db.collection('users').find({
...
0
votes
1
answer
91
views
MongoDB: rename a field with dot in it
I have a MongoDB collection that contains several fields with dots, like:
{
"symbol.name": "Some name"
"symbol.state": "Some state"
// etc.
}
Now, ...
0
votes
1
answer
81
views
updateMany setting field to size of filter condition with not in array
I have a document like this:
{
id: string,
subDocCount: number,
subDocs: [
{
id: string (not an ObjectId),
dateField: Date,
booleanField: boolean
}
]
}
I want to set ...
0
votes
0
answers
23
views
Invalid definition of location schema stated
The below listed function is not giving captains in radius data while creating a ride with user. It is accepting the latitude and longitude. I tried to log the data at every step, whole code is ...
1
vote
1
answer
66
views
Is a localField $lookup faster than a pipeline?
In MongoDB (version 8) I'm wondering about the most read-efficient way of storing a "sharing mechanism". I.e. the users can share items with other items within the same collection.
When ...
0
votes
1
answer
30
views
mongodb_mongod_metrics_ttl_deleted_documents_total seeing this metric in graph
Hi so we have a few collections in my mongo db. for which we have normal indexes created other than primary key. none of those index are ttl indexes. but in mongo db graph we keen seeing ttl delete ...
0
votes
0
answers
33
views
How to manage a field in mongodb that references a referenced schema?
I have a collection named ‘policies’ which references control in its field 'associatedControls' from collection ‘controls’ and control has a field 'associatedFrameworks' where it references 'framework'...
0
votes
0
answers
60
views
C# MongoDB AllMatchingElements Expression not supported
I'm trying to update the subArray elements by the key, adding the value. I'm using the latest version of the library. In the new approach, the "AllMatchingElements" method is used. It seems ...
0
votes
1
answer
58
views
mongodb push update based on ne and arrayfilters not working
I'm trying to create a patch API for a database of products in a MERN application that keeps track of expiry dates.
The idea is when a product's UPC is given, as well as the date in which it expires, ...
1
vote
1
answer
68
views
Should the mongodb index minimize the total keys examined or the total docs examined?
For a particular type of query, I have the choice between 2 indexes.
I ran an example of the query with hint and explain to compare them, with the following output:
Metric
Index 1
Index 2
nReturned
1 ...
2
votes
1
answer
91
views
MongoDB - Update array with $addToSet and set array's length with { '$size': '$array' } not working
I am working on MongoDB, which has a model as below:
const appJobSchema = new mongoose.Schema({
data: [
{ type: Schema.Types.Mixed }
],
stat: {
dataCount: { type: Number, ...
2
votes
1
answer
116
views
Why are multiple $first in a group way slower then just one
We do have a collection with around 20million documents of this structure:
{
_id: ...
learnerId: <string>
type: <string>
organizationId: <string>
timestamp: ISODate
...
1
vote
2
answers
60
views
Converting csv (";" based) string value of a field to new key:value items in same document in Mongodb aggregate
Sample documents of a collection
DB: MYDB
Collection: MYCOLL
{
"_id": {
"$oid": "678a78375cb6955814197272"
},
"ID": 1019397,
"INFO&...
0
votes
0
answers
35
views
When performing a geospatial query, why do the `2d`, and `2dsphere` indexes yield different results for `$near` and `$nearSphere`?
IIUC, $near calculates the Euclidean distance using latitude, and longitude (which I think would be an approximation), whereas $nearSphere calculates the great-circle distance using latitude and ...
-3
votes
1
answer
47
views
How to update nested array object field value in MongoDB? [closed]
Update nested object values in array, we have multiple objects in array.
{
"_id" : ObjectId("5a7e395e20a31e44e0e7e284"),
"name" : "a",
"...
0
votes
1
answer
43
views
MongoDB recursively get documents using multipe fields
Using Mongo 6.0 in a NodeJS application, I have a collection where each document can have an array of mandatoryCourseIds or electiveCourseIds or both.
A sample could look like this:
[
{
&...
1
vote
1
answer
47
views
Deconstruct array field of single document to output documents in Mongo
I am using the following aggregate pipeline in MongoDB to traverse a two-way graph:
{ $match: { from: "some_root" } },
{
$graphLookup: {
from: "connections",
startWith: &...
0
votes
1
answer
72
views
How do I get expected results when searching in MongoDB (Atlas)
Issue
I get "Alice Maria Bobsson" when I search with "Alicex Flicex" (Solution 1)
I don't get "Alice Maria Bobsson" when I search with "Alice Bobsson" (...
1
vote
2
answers
294
views
MongoDB $dateTrunc aggregation operator doesn't return expected value
I was using $dateTrunc on a timeseries collection to group the timeseries data from 2024-12-01 to 2024-12-07 into a single bin.
Here is the aggregate pipeline:
[
{
$match: {
timestamp: {
...
0
votes
1
answer
37
views
Compare coordinate against list of locations
To put it simply I have a list of locations, where each location has it's own long, lat and radius.
I need to check whether an input long, lat is inside any of the locations, so just comparing the ...
0
votes
0
answers
54
views
How could I convert this MongoDB aggregation pipeline updates to Spring Data MongoDB Kotlin/Java code?
Can I convert this aggregation pipeline updates into Spring Data MongoDB(Reactive) with type check?
I mean, it'd be the best if compile error occurs when the name of field in @Document class changes.
...
0
votes
0
answers
70
views
MongoDB Eloquent Models: how to prevent queries targeting 'id' to be rewritten to target '_id'?
I am building a Laravel application on top of a MongoDB instance. For the ORM layer I am using the official MongoDB Driver / Eloquent Implementation.
The DB contains JSON documents that have been ...
0
votes
0
answers
40
views
How to create search index for an attribute and query it which has nested dynamic fields in mongoDB atlas search?
I want to create an index on qualityConfirmations attribute and query it. As qualityConfirmations has dynamic fields at the root level for eg. 228, 234, and inside that I need to query for "...
0
votes
1
answer
196
views
mongoDB $lookup with $search pipeline
I have two collections:
store_group collection:
{"_id": ObjectId("674fe7cc4e65df54a0db23b5"),
"stores": [
{"id": 101, "name":"abc&...
0
votes
0
answers
87
views
How to create wildcard index in monodb atlas search index?
I am using MongoDB Atlas, and my data is stored like this:
{"abc": "123"},
{"def": "456"}
]
Now, I want to create a search index on this collection with ...
0
votes
2
answers
83
views
Is there performance issue if I use multiple "$set" in one update
The data in mongodb is like this
{
"_id": "1",
"a": 1,
"b": 2,
"c": 3
"d": 4
}
I can update the document using a single ...