Mongotemplate using aggregation code to match two fileds from different collections, and if it matches then display the value of the fields - mongodb

I have a mongo db collection
"toss_winner" : {
"player_id" : "1001",
"player_name" : "dinesh",
"rating_value" : 800.0,
"room_id" : "ROOM02",
"is_host" : true,
"player_status" : "ACTIVE",
"table_type_id" : "2",
"user_type" : "USER",
"avatar_id" : NumberInt(4),
"game_type_id" : "2"
}
"toss_map" : {
"110156" : {
"rank" : "8",
"suit" : "S"
},
"1001" : {
"rank" : "K",
"suit" : "C"
}
}
In the toss_map collection I have 2 userId's with the 'rank' and 'suit' and in toss_winner collection, I have player_id field. If the player_id field matches with the toss_map fields, display the
values from the toss_map respective userId.
I am expecting something like this from the above collection
{
"toss_card":{
"rank":"k",
"suit":"c"
}
}

Related

Mongo query to check whether subobject exist or not

I have a collection invoice with subobject address.'invoiceId' is the key of main object(Invoice) and '130704432ST'is key for address(address subobject is saved as Map(key,value) pair).I need to check whether this subobject exists or not, if exist I need to update this. So while querying it gives no object found for below query. I am using spring Mongotemplate query in my application. So my query looks like below.
Kindly share if you find any issues with this query and also help me with Mongo query to execute in Robo 3T 1.2 for below criteria.
Query: { "_id" : { "$java" : 144068830 }, "addresses.144068830SF" : { "$exists" : true } }, Fields: { }, Sort: { }
{
"_id" : {
"invoiceId" : 130704432
},
"destStoreNbr" : 82,
"invoiceTypeCd" : "M",
"countryCode" : "US",
"invoiceNumber" : "0000000086 ",
"totalAmt" : 1038.76,
"invoiceId" : 130704432
"addresses" : {
"130704432ST" : {
"streetAddress4" : "",
"name" : "kEN-MART",
"streetAddress3" : "",
"invAddrTypeCode" : "ST",
"streetAddress2" : "",
"zipCode" : "310310",
"cityName" : "ATLANTA",
"countryCode" : "US",
"stateCode" : "AL"
}
}

Getting array of object with limit and offset doesn't work using mongodb

First let me say that I am new to mongodb. I am trying to get the data from the collection
Here is the document in my collection student:
{
"_id" : ObjectId("5979e0473f00003717a9bd62"),
"id" : "l_7c0e37b9-132e-4054-adbf-649dbc29f43d",
"name" : "Raj",
"class" : "10th",
"assignments" : [
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc571",
"name" : "1"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc572",
"name" : "2"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc573",
"name" : "3"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc574",
"name" : "4"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc575",
"name" : "5"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc576",
"name" : "6"
}
]
}
the output which i require is
{
"assignments" : [
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc571",
"name" : "1"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc572",
"name" : "2"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc573",
"name" : "3"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc574",
"name" : "4"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc575",
"name" : "5"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc576",
"name" : "6"
}
]
}
for this response i used the following query
db.getCollection('student').find({},{"assignments":1})
Now what exactly I am trying is to apply limit and offset for the comments list I tried with $slice:[0,3] but it gives me whole document with sliced result
but not assignments alone so how can I combine these two in order to get only assignments with limit and offset.
You'll need to aggregate rather than find because aggregate allows you to project+slice.
Given the document from your question, the following command ...
db.getCollection('student').aggregate([
// project on assignments and apply a slice to the projection
{$project: {assignments: {$slice: ['$assignments', 2, 5]}}}
])
... returns:
{
"_id" : ObjectId("5979e0473f00003717a9bd62"),
"assignments" : [
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc573",
"name" : "3"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc574",
"name" : "4"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc575",
"name" : "5"
},
{
"id" : "v_539f65c2-9f45-4d92-b05e-973cf08cc576",
"name" : "6"
}
]
}
This represents the assignments array (and only the assignments array) with a slice from element 2 to 5. You can change the slice arguments (2, 5 in the above example) to apply your own offset and limit (where the first argument is the offset and the limit is the difference between the first and second arguments).
If you want to add a match condition (to address specific documents) to the above then you'd do something like this:
db.getCollection('other').aggregate([
/// match a specific document
{$match: {"_id": ObjectId("5979e0473f00003717a9bd62")}},
// project on assignments and apply a slice to the projection
{$project: {assignments: {$slice: ['$assignments', 2, 5]}}}
])
More details on the match step here.

Query inner value in mongoDB

all
I'm trying to do a join in MongoDB but also, I need to check for conditions and to do a sum on inner values of what comes back from the join.
I will explain.
Currently I have this simple join query which looks like this:
db.Sets.aggregate([
{
$lookup:
{
from: "ExecutionTasks",
localField: "identifier",
foreignField: "setIdentifier",
as: "execTask"
}
}
])
It returns the following results:
/* 1 */
{
"_id" : 1,
"name" : "Demo Set",
"identifier" : "demo-set",
"description" : "Demo Set",
"creator" : {
"id" : 1,
"name" : "admin"
},
"createdDate" : ISODate("2017-03-24T20:09:55.120Z"),
"updatedDate" : ISODate("2017-03-24T20:09:55.120Z"),
"execTask" : [
{
"_id" : 1,
"isActive" : 1,
"type" : "count",
"threshold" : {
"default" : "0",
"deviations" : []
},
"name" : "amishay",
"setIdentifier" : "demo-set",
"description" : "a",
"query" : {
"source" : 1,
"text" : "select * from t"
},
"creator" : {
"id" : 1,
"name" : "admin"
},
"createdDate" : ISODate("2017-03-27T20:03:22.275Z"),
"updatedDate" : ISODate("2017-03-27T20:03:22.275Z")
},
{
"_id" : 2,
"isActive" : 0,
"type" : "count",
"threshold" : {
"default" : "0",
"deviations" : []
},
"name" : "amishay2",
"setIdentifier" : "demo-set",
"description" : "test",
"query" : {
"source" : 1,
"text" : "select * from t"
},
"creator" : {
"id" : 1,
"name" : "admin"
},
"createdDate" : ISODate("2017-03-27T20:03:57.248Z"),
"updatedDate" : ISODate("2017-03-27T20:03:57.248Z")
}
]
}
What I would like to do is to return only the length of the array (execTask) and also only those with the attribute isActive which equals to 1.
So basically I want to get something like:
{
"_id" : 1,
"name" : "Demo Set",
"identifier" : "demo-set",
"description" : "Demo Set",
"creator" : {
"id" : 1,
"name" : "admin"
},
"createdDate" : ISODate("2017-03-24T20:09:55.120Z"),
"updatedDate" : ISODate("2017-03-24T20:09:55.120Z"),
"execTask" : 1
}
I checked online numerous questions but I only saw examples which query the collection attribute and not the joined collection attribute.
Thanks!
You can add $addFields stage after $lookup. The below stage will $filter and calculate the $size for query criteria.
$filter operator is to used to filter the execTask array contents in-place on the mentioned criteria.
Expressions $ and $$ to reference the fields / aggregation operators / aggregation stages and inner variables respectively.
$size operator to calculate the length of filtered array.
$addFields overwrites the existing field execTask to replace its value with the calculated size.
{
$addFields: {
"execTask": {
$size: {
$filter: {
input: "$execTask",
as: "result",
cond: {
$eq: ["$$result.isActive", 1]
}
}
}
}
}
}

Mongodb - Return all the associative documents with value for the key derived from another query

I have a document of following structure:
{
"Type" : "Request",
"Cat" : "A",
"ID" : 10
}
{
"Type" : "Processed",
"Cat" : "A",
"ID" : 10
}
{
"Type" : "Receieved",
"Cat" : "A",
"ID" : 10
}
{
"Type" : "Receieved",
"Cat" : "B",
"ID" : 11
}
{
"Type" : "Processed",
"Cat" : "C",
"ID" : 12
}
I want documents:
Those documents with Type: "Processed" and get its ID
And all the associated documents with the ID got from above (1st step).
I need the results to be like this:
{
"Type" : "Request"
"Cat" : "A"
"ID" : 10
}
{
"Type" : "Processed"
"Cat" : "A"
"ID" : 10
}
{
"Type" : "Receieved"
"Cat" : "A"
"ID" : 10
}
{
"Type" : "Processed"
"Cat" : "C"
"ID" : 12
}
Can someone help me on how to achieve this ? I used elemmatch under $match in aggregate - but its not working as expected.
You can try something like
db.collection.aggregate([
{$project : {
"ID":1,
"doc.Type" : "$Type",
"doc.Cat" : "$Cat",
"doc.ID" : "$ID"
}
}
{$group : {
_id : "$ID",
docs : {$push : doc}
}
},
{$match : {
"docs.Type":"Processed"
}
},
{$unwind : "$docs"},
{$project : {
_id : 0,
docs : 0,
"Type" : "$docs.Type",
"Cat" : "$docs.Cat",
"ID" : "$docs.ID"
}
}
])

how to use aggregation of mongodb

From the data as given below, I want to sum all Values fields.
Please let me know how can I do it using aggregation functionality of mongodb.
{"MetricRecord":
{ "SchemaVersion" : "0.12",
"Product": {
"ProductName" : "abc",
"ProductVersion": "7.5.0.1" ,
"ProductId" : "1234567890ABDFGH12345",
"InstanceId" : "12345BA32",
"InstanceName" : "1234SS123",
"SystemId" : "somehost.com"
},
"Tenant" : {
"CustomerId" : "222-555-124",
"ServiceCode": "xyzxyzxyz12345yyy"
},
"Metrics" : [
{
"ReportType" :[
{ "report" : "billing" },
],
"LogTime" : "2013-12-08T12:34:56:01Z" ,
"Type" : "AuthorizedUsers",
"SubType" : "registered",
"Value" : "125",
"UnitOfMeasure": "USD",
"Period" : {
"StartTime" : "2013-12-07T00:00:00:01Z",
"EndTime" : "2013-12-08T00:00:00:01Z"
}
},
{
"ReportType" :[
{ "report" : "billing" }
],
"LogTime" : "2013-12-08T12:34:56:01Z" ,
"Type" : "NumberOfTickets",
"SubType" : "resolved",
"Value" : "430",
"UnitOfMeasure": "USD",
"Period" : {
"StartTime" : "2013-12-07T00:00:00:01Z",
"EndTime" : "2013-12-08T00:00:00:01Z"
}
}
]
}
}
So, results which I expect from summation of values is 430+125 i.e. 555
Your document contains string value for MetricRecord.Metrics[index].Value field and i am not sure why are you trying to sum up the string values. if it is a typo and your document contains numerical values for MetricRecord.Metrics[index].Value field then you can try the following query
db.metrics.aggregate([
{$unwind:"$MetricRecord.Metrics"},
{$group:{_id:"$_id",sum:{$sum:"$MetricRecord.Metrics.Value"}}}
])
In the above document posted, if your value field is like
MetricRecord.Metrics[0].Value is 125(not "125")
MetricRecord.Metrics[1].Value is 430(not "430")
you will get the following output
{
"result" : [
{
"_id" : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
"sum" : 555
}
],
"ok" : 1
}
The above sample query is composed assuming you have the default mongodb "_id" field and you are using a metrics collection. You have to manipulate the query as per you requirements.