Aggregation result of two values within the same document in MongoDB - mongodb

I have a MongoDB 3.6 database and I have several documents in one collection.
All documents have the same properties like:
{"type": "stuff", "price1": 2, "price2": 5, "total_cost": }
I would like to have the sum of price1 and price2 as value for total_cost, is it possible to do that?
And if I update price1 or price2, it will update automatically total_cost.
{"type": "stuff", "price1": 2, "price2": 5, "total_cost": 7 }
Thanks a lot!

You can search about the $out stage of the aggregation pipeline, but I think it will create a new collection in your database. To do your job, you need to compute your total in your code and $set after the result in your document.

Related

mongodb query with $in record with subsequent condition

My dataset is like the below, where _v is the version of the document (after changes).
record id:1, _v: 1
record id:2, _v: 2
record id:3, _v: 3
Is there a way to query this by passing in the id (i am using $in now) AND check if the corresponding _v is not matching? For example if my input is {id: 3, version:1}. I need it retrieved because the database has the latest version as 3 (_v:3)
Thanks!
You can negate your version check with $ne.
db.collection.find({
id: {$in: [3]},
_v: {$ne: 1}
})

MongoDB summing field of document during query

I want to execute a mongodb query that would fetch documents until the sum of a field of those documents exceeds a value. For example, if I have the following documents
{id: 1, qty: 40}
{id: 2, qty: 50}
{id: 3, qty: 30}
and I have a set quantity of 80, I would want to retrieve id1 and id2 because 40+50 is 90 and is now over 80. If I wanted a quantity of 90, I would also retrieve id1 and id2. Does anyone have any insight into how to query in this manner? (I'm using Go btw - but any general mongo query advice would help tremendously)
Since you're keeping a running sum of a certain field, the easiest way of doing this is running a Find operation, get a cursor, and iterate the cursor while keeping the sum yourself until the required total is reached. Then, close the cursor and return:
cursor, err:=coll.Find(context.Background(),query)
sum:=0
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
cursor.Decode(&data)
sum+=data.Qty
if sum>=80 {
break
}
}

MongoDB result as aggregated array of fields, not array of objects [duplicate]

This question already has answers here:
How do I get a list of just the ObjectId's using pymongo?
(5 answers)
Closed 5 years ago.
I have collection of documents (~1 billion of items) and I want to get it as array of field. And in the same time I do not want to postprocess result of Mongo query.
Example:
// Collection looks alike
[
{"_id": ObjectId("...", "id": "12313123", ....)},
{"_id": ObjectId("...", "id": "35675468456", ....)}
{"_id": ObjectId("...", "id": "23233463", ....)}
....
]
// Desired result
["12313123", "35675468456", "23233463"]
I.e I want to get only field id and make result flatten. But statement
db.collection.find({}, {"_id": 0, "id": 1}) returns list of objects.
Would single-purpose aggregation db.collection.distinct("id") work for you?

Optimising queries in mongodb

I am working on optimising my queries in mongodb.
In normal sql query there is an order in which where clauses are applied. For e.g. select * from employees where department="dept1" and floor=2 and sex="male", here first department="dept1" is applied, then floor=2 is applied and lastly sex="male".
I was wondering does it happen in a similar way in mongodb.
E.g.
DbObject search = new BasicDbObject("department", "dept1").put("floor",2).put("sex", "male");
here which match clause will be applied first or infact does mongo work in this manner at all.
This question basically arises from my background with SQL databases.
Please help.
If there are no indexes we have to scan the full collection (collection scan) in order to find the required documents. In your case if you want to apply with order [department, floor and sex] you should create this compound index:
db.employees.createIndex( { "department": 1, "floor": 1, "sex" : 1 } )
As documentation: https://docs.mongodb.org/manual/core/index-compound/
db.products.createIndex( { "item": 1, "stock": 1 } )
The order of the fields in a compound index is very important. In the
previous example, the index will contain references to documents
sorted first by the values of the item field and, within each value of
the item field, sorted by values of the stock field.

How to fetch between a range of indexes in mongodb?

I need help.. Is there any method available to fetch documents between a range of indexes while using find in mongo.. Like [2:10] (from 2 to 10) ?
If you are talking about the "index" position within an array in your document then you want the $slice operator. The first argument being the index to start with and the second is how many to return. So from a 0 index position 2 is the "third" index:
db.collection.find({},{ "list": { "$slice": [ 2, 8 ] })
Within a collection itself if you use the .limit() an .skip() modifiers to move through the range in the collection:
db.collection.find({}).skip(2).limit(8)
Keep in mind that in the collection context MongoDB has no concept of "ordered" records and is dependent on the query and/or sort order that is given