I have following documents in collection.
{
"_id": Object('sjaflj'),
"employee_id": "23849823432",
"name": "employee-1",
"department": "department-1",
"type": "manager",
"associations" : [
{
"name" : "associated_components",
"values" : [
"45c10396cefa7351b1ddadf6d6a29c37"
]
}
]
}
# Document-2
{
"_id": Object('sjafljwerq'),
"employee_id": "45c10396cefa7351b1ddadf6d6a29c37",
"name": "employee-2",
"department": "department-1",
"type": "employee",
"associations" : [
{
"name" : "associated_components",
"values" : []
}
]
}
I am fetching documents from db based on name, department, type. i would like to fetch all child-document if the type of record is "manager".
The child-records's key attached to manager is in the associations-->values.
How i can get all the records + child-records from collection using single query. ?
Please suggest some ideas, it will be very helpful. thanks.
Related
I have my monogdb departments data structure like as shown below
[{
category: "ABC",
sections: [
{
section_hod: "x111",
section_name: "SECTION A",
section_staff_count: "v11111",
section_id: "a1111",
:
},
{
section_hod: "x2222",
section_name: "SECTION B",
section_staff_count: "v2222",
section_id: "a2222",
:
}
]
}
:
:
]
I wrote a mongodb query like as shown below
db.getSiblingDB("departments").getCollection("DepartmentDetails").aggregate([
{ $unwind : "$sections"},
{ $match : { $and : [{ "sections.section_name" : "SECTION A"},
{ $or : [{ "category" : "ABC"}]}]}},
{$project : { "name" : "$sections.section_name", "hod" : "$sections.section_hod", "staff_count" : "$sections.section_staff_count", "id" : "$sections.section_id"}},
{$skip: 0}, {$limit: 10}
]);
which gives me a list of section details as shown below which contains name, hod, staff_count, id etc
[
{
"name": "xxxxx",
"hod": "xxxxx",
"staff_count": "xxxxx",
"id": "xxxxx"
},
{
"name": "yyyyy",
"hod": "yyyyy",
"staff_count": "yyyyy",
"id": "yyyyy"
}
:
:
:
]
Everything looks good, but the problem is I have so many records in the list with which I am trying to build a pagination. For implementing pagination I know I can use the skip and limit function for iterating the pages, but for doing that I need to know the total counts of all the records.
I can do this in two ways, First way is I can execute two queries one which will be a count and then the aggregate query passing the skip and limit, second way is execute one query which return me the total counts and the documents in the order of first paginated page.
I am trying to implement the second way and bring the expected result is as shown below
{
"documents": [
{
"name": "xxxxx",
"hod": "xxxxx",
"staff_count": "xxxxx",
"id": "xxxxx"
},
{
"name": "yyyyy",
"hod": "yyyyy",
"staff_count": "yyyyy",
"id": "yyyyy"
}
:
:
:
],
"totalCount": 5444
}
Not sure if this is achievable. Can someone please help me on this. My default limit is 10
You can do it like this, it will give you total records and paginated results in one go,
db.getSiblingDB("departments").getCollection("DepartmentDetails")
.aggregate([
{ $unwind : "$sections"},
{ $match : { $and : [{ "sections.section_name" : "SECTION A"},
{ $or : [{ "category" : "ABC"}]}]}},
{
$project : {
"name" : "$sections.section_name",
"hod" : "$sections.section_hod",
"staff_count" : "$sections.section_staff_count",
"id" : "$sections.section_id"
}
},
{
$facet: {
metaData: [{
$count: 'total'
}],
records: [
{$skip: 0},
{$limit: 10}
]
}
},
{
$project: {
records: 1,
total: {
$let: {
vars: {
totalObj: {
$arrayElemAt: ['$metaData', 0]
}
},
in: '$$totalObj.total'
}
},
}
}
]);
I am new to mongodb, I have a requirement and would like to know how to generate custom resultset using Mongo aggregate operator. Any help would be appreciated.
Need to group the collection by "company" and "status" and would need to produce resultset given below.
Collection
[
{
"company": "google",
"status": "active",
"offer": {
"job": "developer",
"salary": 10000.00
},
},
{
"company": "google",
"status": "active",
"offer": {
"job": "designer",
"salary": 500000.00
},
},
{
"company": "amazon",
"status": "inactive",
"offer": {
"job": "designer",
"salary": 500000.00
},
}
]
Expected Result-Set
[
{
"company" : "google",
"report" : [{
"status" : "active",
"totalSalary" : 60000
},
{
"status" : "inactive",
"totalSalary" : 0
}]
},
{
"company" : "amazon",
"report" : [{
"status" : "active",
"totalSalary" : 0
},
{
"status" : "inactive",
"totalSalary" : 500000.00
}]
}
]
You should 100% check the official documentation on aggregates, it's a bit complicated at first but once you get the hang of it they're great. I also recommend you https://mongoplayground.net/, it's a great site for doing this kind of tests.
What you're looking for is something like this
db.collection.aggregate([
{
$group: {
_id: {
company: "$company"
},
report: {
$addToSet: "$offer"
}
}
}
])
You can test it here. You also probably want to rename the resulting _id field that's mandatory in a group aggregate. You can find how to do that here
Below is the JSON structure for a Store document:
{
{
"_id":"87348378",
"name": "ABC store",
"type": "Books",
"books": [
{
"name": "love",
"id": "1",
"types":{
"type":"love",
"number":"1"
}
},
{
"name": "coreman",
"id": "2",
"types":{
"type":"love",
"number":"1"
}
}
]
},
{
"_id":"87348",
"name": "Some store",
"type": "Books",
"books": [
{
"name": "JAVA",
"id": "1",
"types":{
"type":"Programming",
"number":"2"
}
},
{
"name": "coreman",
"id": "2",
"types":{
"type":"Programming",
"number":"3"
}
}
]
}
}
I need to get the all the stores, which are of a Bookstore type. But, I just want to return certain fields from the Books array(Name & type from types)
Using the following query to get the result:
db.getCollection('store').aggregate([{
"$project" : { "name" : 1 , "type" : 1 ,
"books":{"name":1,"types":{"type":1}}}
},
{ "$group" : { "_id" : "$type",
"books" : { "$push" : "$$ROOT"}}}])
Could anyone help me out to generate the same query with Spring/Java.
Note: I have seen addInclude method has like below in spring docs.
reference: https://docs.spring.io/spring-data/data-mongo/docs/current/api/org/springframework/data/mongodb/core/aggregation/ProjectionOperation.html
**org.springframework.data.mongodb.core.aggregation**
andInclude
public ProjectionOperation andInclude(String... fieldNames)
Includes the given fields into the projection.
Parameters:
fieldNames - must not be null.
Returns:
andInclude
public ProjectionOperation andInclude(Fields fields)
Includes the given fields into the projection.
Parameters:
fields - must not be null.
Returns:
im having trouble with mongodb querying
my object document:
[
{
"_id": "5a2ca2227c42ad67682731d4",
"name": "name",
"photos": [
{
"_id": "5a2ca22b7c42ad67682731d5",
"approved": false,
"text":"good"
},
{
"_id": "5a2ca72b0a1aa173aaae07da",
"approved": true,
"text":"bad"
}
]
},
{
"_id": "4v2ca2227cad676821731d4",
"name": "name"
}
]
im trying to query all documents.. in this documents, the documents somethings will have photos, if exists , would like to bring the photos that have attribute approved equals to true.. but i have to bring all documents, thoses who have photos, and those who not.. im trying to use aggregation, project, unwind, but im not got any good result yet :(
i need the results be like :
[
{
"_id": "5a2ca2227c42ad67682731d4",
"name": "name",
"photos": [
{
"_id": "5a2ca22b7c42ad67682731d5",
"approved": false,
"text":"good"
}
]
},
{
"_id": "4v2ca2227cad676821731d4",
"name": "name"
}
]
thank you!
You might need to $unwind all including the non existing photos array for getting the results
db.ph.aggregate(
[
{
$unwind:
{
path: "$photos",
preserveNullAndEmptyArrays: true
}
},
{
$match : {"photos.approved" : {$ne : true} }
}
]
)
result
{
"_id" : "5a2ca2227c42ad67682731d4",
"name" : "name",
"photos" : {
"_id" : "5a2ca22b7c42ad67682731d5",
"approved" : false,
"text" : "good"
}
}
{ "_id" : "4v2ca2227cad676821731d4", "name" : "name" }
>
This question has previously been marked as a duplicate of this question I can with certainty confirm that it is not.
This is not a duplicate of the linked question because the elements in question are not an array but embedded in individual objects of an array as fields. I am fully aware of how the query in the linked question should work, however that scenario is different from mine.
I have a question regarding the $lookup query of MongoDb. My data structure looks as follows:
My "Event" collection contains this single document:
{
"_id": ObjectId("mongodbobjectid..."),
"name": "Some Event",
"attendees": [
{
"type": 1,
"status": 2,
"contact": ObjectId("mongodbobjectidHEX1")
},
{
"type": 7,
"status": 4,
"contact": ObjectId("mongodbobjectidHEX2")
}
]
}
My "Contact" collection contains these documents:
{
"_id": ObjectId("mongodbobjectidHEX1"),
"name": "John Doe",
"age": 35
},
{
"_id": ObjectId("mongodbobjectidHEX2"),
"name": "Peter Pan",
"age": 60
}
What I want to do is perform an aggregate query with the $lookup operator on the "Event" collection and get the following result with full "contact" data:
{
"_id": ObjectId("mongodbobjectid..."),
"name": "Some Event",
"attendees": [
{
"type": 1,
"status": 2,
"contact": {
"_id": ObjectId("mongodbobjectidHEX1"),
"name": "John Doe",
"age": 35
}
},
{
"type": 7,
"status": 4,
"contact": {
"_id": ObjectId("mongodbobjectidHEX2"),
"name": "Peter Pan",
"age": 60
}
}
]
}
I have done the same with single elements of "Contact" referenced in another document but never when embedded in an array. I am unsure of which pipeline arguments to pass to get the above shown result?
I also want to add a $match query to the pipeline to filter the data, but that is not really part of my question.
Try this one
db.getCollection('Event').aggregate([{ "$unwind": "$attendees" },
{ "$lookup" : { "from" : "Contact", "localField" : "attendees.contact", "foreignField": "_id", "as" : "contactlist" } },
{ "$unwind": "$contactlist" },
{ "$project" :{
"attendees.type" : 1,
"attendees.status" : 1,
"attendees.contact" : "$contactlist",
"name": 1, "_id": 1
}
},
{
"$group" : {
_id : "$_id" ,
"name" : { $first : "$name" },
"attendees" : { $push : "$attendees" }
}
}
])