Updating array list in Mongo DB - mongodb

I want to update the Status field inside array list of Slots where id = "".
Sample data
{
"_id": ObjectId("621e816e7a938400016c5c64"),
"Resource": "abc#gmail.com",
"School": {
"Class": [
{
"Type": "ABC",
"Slots": [
{
"id": "",
"Duration": "1 week",
"Status": "Released",
"Selected": true
},
{
"id": "123",
"Duration": "1 week",
"Status": "Released",
"Selected": true
}
]
}
]
}
}
This is how I am approaching:
db.getCollection("XYZ").update({
"Resource": "abc#gmail.com",
"School.Class": {
"$elemMatch": {
"Type": "ABC",
"Slots.Status": "Released",
"Slots.id": "",
"Slots.Duration": "1 week"
}
}
},
{
$set: {
"School.Class.$[outer].Slots.$[inner].Status": "Confirmed"
}
},
{
"arrayFilters": [
{
"outer.Type": "ABC"
},
{
"inner.Duration": "1 week"
}
]
})
But it is updating the status as confirmed for the both the array list.How can I update the particular field where "Slots.id" : "" . Please forgive me in case of any misalignment or brackets missing in data

If I've understood correctly you are almost there, since you want to update only values where id is "" you have to add that condition into arrayFilters: "inner.id": "".
db.collection.update({
"Resource": "abc#gmail.com",
"School.Class": {
"$elemMatch": {
"Type": "ABC",
"Slots.Status": "Released",
"Slots.id": "",
"Slots.Duration": "1 week"
}
}
},
{
$set: {
"School.Class.$[outer].Slots.$[inner].Status": "Confirmed"
}
},
{
"arrayFilters": [
{
"outer.Type": "ABC"
},
{
"inner.Duration": "1 week",
"inner.id": "" // <--- This line
}
]
})
Example here

Related

How to sum values using unwind in MongoDB with Spring Data

When using unwind("items") each item produces a duplicate line. This leads to revenue being counted as many times as there are items.
Example: Someone buys 1 item of A and 1 item of B, resulting in a cummulative value of 10. Unwind now inserts a row for each item, leading to a sum(cummulative) of 20.
I tried grouping the elements directly after unwind but have not managed to get it to work properly.
How can I sum each array element without duplication every other value?
I have this data structure
{
"_id": {
"$binary": "VEE6CsjHPvjzS2JYso7mnQ==",
"$type": "3"
},
"sequentialId": {
"$numberLong": "1"
},
"date": "2022-02-04",
"invoiceTotal": {
"$numberDecimal": "9.85"
},
"vatTotal": {
"$numberDecimal": "0"
},
"vatPercentage": {
"$numberDecimal": "19.00"
},
"invoiceNumber": "1111111",
"type": "ELEKTRONISCH",
"aktivkonto": 2800,
"passivkonto": 5200,
"buyerEmail": "",
"username": "",
"shop": "",
"externalId": "",
"shipped": false,
"actualShippingCost": {
"$numberDecimal": "1"
},
"filename": "",
"isReported": false,
"deliveryCostTotal": {
"$numberDecimal": "4.35"
},
"items": [
{
"lineItemId": "",
"amount": "1",
"sku": "A123123",
"title": "",
"priceTotal": {
"$numberDecimal": "4.50"
},
"vatTotal": {
"$numberDecimal": "0"
},
"hardwareCostPerPiece": {
"$numberDecimal": "0.22"
},
"hardwareCostTotal": {
"$numberDecimal": "0.22"
}
},
{
"lineItemId": "",
"amount": "1",
"sku": "B212312",
"title": "",
"priceTotal": {
"$numberDecimal": "1.00"
},
"vatTotal": {
"$numberDecimal": "0"
},
"hardwareCostPerPiece": {
"$numberDecimal": "0.22"
},
"hardwareCostTotal": {
"$numberDecimal": "0.22"
}
}
],
"packagingCost": {
"$numberDecimal": "0.15"
},
"hasInvoiceSent": false,
"tenant": "you!",
"createdAt": {
"$date": "2022-02-04T15:23:40.716Z"
},
"modifiedAt": {
"$date": "2022-02-04T15:23:40.716Z"
},
"_class": "_.RevenueEntity"
}
and this query
fun sumAllByWeeklyAndTenant(tenant: String): Flux<DashboardRevenue> {
val aggregation = newAggregation(
match(findByTenant(tenant)),
unwind("items"),
group("invoiceNumber")
.sum("items.hardwareCostTotal").`as`("hardwareCostTotal"),
project()
.andExpression("year(createdAt)").`as`("year")
.andExpression("week(createdAt)").`as`("week")
.andInclude(bind("hardwareCostTotal", "items.hardwareCostTotal"))
.andInclude(
"invoiceTotal",
"vatTotal",
"actualShippingCost",
"packagingCost",
"marketplaceFeesTotal",
"tenant"
),
group("year", "week", "tenant")
.sum("invoiceTotal").`as`("umsatz")
.sum("actualShippingCost").`as`("portokosten")
.sum("packagingCost").`as`("verpackung")
.sum("marketplaceFeesTotal").`as`("marketplaceFees")
.sum("hardwareCostTotal").`as`("hardwareCost")
.sum("vatTotal").`as`("vatTotal")
.count().`as`("numberOfInvoices"),
sort(Sort.Direction.DESC, "year", "week"),
limit(8),
sort(Sort.Direction.ASC, "year", "week")
)
return reactiveMongoTemplate
.aggregate(aggregation, "revenue", DashboardRevenue::class.java)
.toFlux()
}
Using the data above the query results in
[
{
"_id": {
"year": 2022,
"month": 2,
"week": 0,
"tenant": "einsupershop"
},
"umsatz": 19.70,
"portokosten": 2,
"verpackung": 0.30,
"marketplaceFees": 3.42,
"hardwareCost": 0.22,
"vatTotal": 0,
"numberOfInvoices": 2
}
]
Where the expected value is "invoiceTotal": { "$numberDecimal": "9.85" }

Mongo Aggregation using $Max

I have a collection that stores history, i.e. a new document is created every time a change is made to the data, I need to extract fields based on the max value of a date field, however my query keeps returning either all of the dates or requires me to push the fields into an array which make the data hard to analyze for an end-user.
Expected output as CSV:
MAX(DATE), docID, url, type
1579719200216, 12371, www.foodnetwork.com, food
1579719200216, 12371, www.cnn.com, news,
1579719200216, 12371, www.wikipedia.com, info
Sample Doc:
{
"document": {
"revenueGroup": "fn",
"metaDescription": "",
"metaData": {
"audit": {
"lastModified": 1312414124,
"clientId": ""
},
"entities": [],
"docId": 1313943,
"url": ""
},
"rootUrl": "",
"taggedImages": {
"totalSize": 1,
"list": [
{
"image": {
"objectId": "woman-reaching-for-basket",
"caption": "",
"url": "",
"height": 3840,
"width": 5760,
"owner": "Facebook",
"alt": "Woman reaching for basket"
},
"tags": {
"totalSize": 4,
"list": []
}
}
]
},
"title": "The 8 Best Food Items of 2020",
"socialTitle": "The 8 Best Food Items of 2020",
"primaryImage": {
"objectId": "woman-reaching-for-basket.jpg",
"caption": "",
"url": "",
"height": 3840,
"width": 5760,
"owner": "Hero Images / Getty Images",
"alt": "Woman reaching for basket in laundry room"
},
"subheading": "Reduce your footprint with these top-performing diets",
"citations": {
"list": []
},
"docId": 1313943,
"revisionId": "1313943_1579719200216",
"templateType": "LIST",
"documentState": {
"activeDate": 579719200166,
"state": "ACTIVE"
}
},
"url": "",
"items": {
"totalSize": "",
"list": [
{
"type": "recipe",
"data": {
"comInfo": {
"list": [
{
"type": "food",
"id": "https://www.foodnetwork.com"
}
]
},
"type": ""
},
"id": 4,
"uuid": "1313ida-qdad3-42c3-b41d-223q2eq2j"
},
{
"type": "recipe",
"data": {
"comInfo": {
"list": [
{
"type": "news",
"id": "https://www.cnn.com"
},
{
"type": "info",
"id": "https://www.wikipedia.com"
}
]
},
"type": "PRODUCT"
},
"id": 11,
"uuid": "318231jc-da12-4475-8994-283u130d32"
}
]
},
"vertical": "food"
}
Below query:
db.collection.aggregate([
{
$match: {
vertical: "food",
"document.documentState.state": "ACTIVE",
"document.templateType": "LIST"
}
},
{
$unwind: "$document.items"
},
{
$unwind: "$document.items.list"
},
{
$unwind: "$document.items.list.contents"
},
{
$unwind: "$document.items.list.contents.list"
},
{
$match: {
"document.items.list.contents.list.type": "recipe",
"document.revenueGroup": "fn"
}
},
{
$sort: {
"document.revisionId": -1
}
},
{
$group: {
_id: {
_id: {
docId: "$document.docId",
date: {$max: "$document.revisionId"}
},
url: "$document.items.list.contents.list.data.comInfo.list.id",
type: "$document.items.list.contents.list.data.comInfo.list.type"
}
}
},
{
$project: {
_id: 1
}
},
{
$sort: {
"document.items.list.contents.list.id": 1, "document.revisionId": -1
}
}
], {
allowDiskUse: true
})
First of all, you need to go through the documentation of the $group aggregation here.
you should be doing this instead:
{
$group: {
"_id": "$document.docId"
"date": {
$max: "$document.revisionId"
},
"url": {
$first: "$document.items.list.contents.list.data.comInfo.list.id"
},
"type": {
$first:"$document.items.list.contents.list.data.comInfo.list.type"
}
}
}
This will give you the required output.

check if a field of type array contains an array

Im using mongoose, I have the following data of user collection:
[{
"_id": "1",
"notes": [
{
"value": "A90",
"text": "math"
},
{
"value": "A80",
"text": "english"
},
{
"value": "A70",
"text": "art"
}
]
},
{
"_id": "2",
"notes": [
{
"value": "A90",
"text": "math"
},
{
"value": "A80",
"text": "english"
}
]
},
{
"_id": "3",
"notes": [
{
"value": "A80",
"text": "art"
}
]
}]
and I have as a parameters the following array: [ "A90", "A80" ]
so I want to make a query to use this array to return only the records that have all the array items in the notes (value) table.
So for the example above it will return:
[{
"_id": "1",
"notes": [
{
"value": "A90",
"text": "math"
},
{
"value": "A80",
"text": "english"
},
{
"value": "A70",
"text": "art"
}
]
},
{
"_id": "2",
"notes": [
{
"value": "A90",
"text": "math"
},
{
"value": "A80",
"text": "english"
}
]
}]
I tried the following find query:
{ "notes": { $elemMatch: { value: { $in: valuesArray } } }}
but it returns a record even if just one element in valuesArray exist.
it turned out to be quite easy:
find({ "notes.value": { $all: arrayValues } })

MongoDB query, project nested docs?

I was wondering if this is possible, or do I need to use the aggregation pipeline instead?
I have read posts such as this, and intuitively feel like it's possible.
Example of docs:
{
"_id": ObjectID("5143ddf3bcf1bfab37d9c6f"),
"permalink": "btxcacmbqkxbpgtpeero",
"author": "machine",
"title": "Declaration of Independence",
"tags": [
"study",
"law"
],
"comments": [
{
"body": "comment 1",
"email": "email_1#test.com",
"author": "machine_1"
},
{
"body": "comment 2",
"email": "email_2#test.com",
"author": "machine_2"
},
{
"body": "comment 3",
"email": "email_3#test.com",
"author": "machine_3"
},
]
"date": ISODate("2013-03-16T02:50:27.878Z")
}
I am trying to access a particular comment in "comments" by it's index position using dot notation in the projection field, with the following:
db.collection.find({permalink: "btxcacmbqkxbpgtpeero"}, {'comments.0.1.': 1})
Where comments.0 is the first item in the field: the array, and .1 is the second comment in the array.
The result I am getting:
{ "_id" : ObjectID("5143ddf3bcf1bfab37d9c6f"), "comments" : [ { }, { }, { } ] }
If I take away the .1, leaving just comments.0, I get the same result:
{ "_id" : ObjectID("5143ddf3bcf1bfab37d9c6f"), "comments" : [ { }, { }, { } ] }
If I take away the .0, leaving just comments, I get the comments still inside their array:
[
{
"body": "comment 1",
"email": "email_1#test.com",
"author": "machine_1"
},
{
"body": "comment 2",
"email": "email_2#test.com",
"author": "machine_2"
},
{
"body": "comment 3",
"email": "email_3#test.com",
"author": "machine_3"
}
]
Can this be done? If so, how?
without aggregation:
db.collection.find({
permalink:"btxcacmbqkxbpgtpeero"
},
{
comments:{
$slice:[
0,
1
]
}
})
returns
{
"_id":ObjectId("583af24824168f5cc566e1e9"),
"permalink":"btxcacmbqkxbpgtpeero",
"author":"machine",
"title":"Declaration of Independence",
"tags":[
"study",
"law"
],
"comments":[
{
"body":"comment 1",
"email":"email_1#test.com",
"author":"machine_1"
}
]
}
try it online: mongoplayground.net/p/LGbVWPyVkFk
with aggregation:
db.collection.aggregate([
{
$match:{
permalink:"btxcacmbqkxbpgtpeero"
}
},
{
$project:{
comment:{
$arrayElemAt:[
"$comments",
0
]
}
}
}
])
returns
{
"_id":ObjectId("583af24824168f5cc566e1e9"),
"comment":{
"body":"comment 1",
"email":"email_1#test.com",
"author":"machine_1"
}
}

MongoDB - Query within an in-memory BsonDocument

I am reading a single document into a BsonDocument object. Having read the document from MongoDB I'd like to query the document in-memory.
My doc looks like this:
{
"_id": {
"$binary": "DYibd4bSz0SFXTTmY46gOQ==",
"$type": "03"
},
"title": "XYZ 2011",
"pages": [
{
"pagetype": "contactcapture",
"pagetitle": "Contact",
"questions": [
{
"qtype": "text",
"text": "Firstname",
"name": "firstname"
},
{
"qtype": "text",
"text": "Surname",
"name": "surname"
},
{
"qtype": "text",
"text": "Company",
"name": "companyname"
}
]
},
{
"pagetype": "question",
"pagetitle": "Question 1",
"questions": [
{
"qtype": "radio",
"text": "What drink?",
"name": "drink",
"answers": [
{
"text": "Tea"
},
{
"text": "Coffee"
},
{
"text": "Hot chocolate"
},
{
"text": "Water"
}
]
}
]
},
{
"pagetype": "question",
"pagetitle": "Question 2",
"questions": [
{
"qtype": "check",
"text": "Accompaniments?",
"name": "accompaniments",
"answers": [
{
"text": "Nuts"
},
{
"text": "Crisps"
},
{
"text": "Biscuits"
}
]
}
]
},
{
"pagetype": "question",
"pagetitle": "Question 3",
"questions": [
{
"qtype": "radio",
"text": "When would you like that?",
"name": "when",
"answers": [
{
"text": "Immediately"
},
{
"text": "10 minutes"
},
{
"text": "Half-an-hour"
}
]
},
{
"qtype": "text",
"text": "Anything else with that?",
"name": "anythingelse"
}
]
}
]
}
I want to get all pages that have a pagetype="question". I'm currently doing it as follows:
BsonDocument profileDocument= profilesCollection.FindOneByIdAs<MongoDB.Bson.BsonDocument>(binaryId);
BsonElement pagesElement = profileDocument.GetElement("pages");
BsonArray pages=profileDocument.GetElement("pages").Value.AsBsonArray;
foreach (BsonValue pageV in pages.Values)
{
BsonDocument page = pageV.AsBsonDocument;
if (page["pagetype"].AsString == "question")
{
sb.Append("<br />Question Page:" + page.ToJson());
}
}
The code seems a little verbose and complex - I just wondered if there is a better way of doing this? Thanks
Assuming that the data type of profilesCollection is MongoCollection<BsonDocument>, you could shorten the code so something like this:
var profileDocument = profilesCollection.FindOneById(binaryId);
foreach (BsonDocument page in profileDocument["pages"].AsBsonArray) {
if (page["pagetype"].AsString == "question") {
sb.Append("<br />Question Page:" + page.ToJson());
}
}