How to query an array in an array of objects in mongodb? - mongodb

I am pretty new to mongodb, and I am not able to query in my mongo collection.
Structure :
"chapterId":1,
"videos" : [
{
"videoId" : "1",
"videoName" : "about",
"duration" : "12:36",
"tags":["business", "design"]
},
{
"videoId" : "2",
"videoName" : "course",
"duration" : "04:00",
"tags":["technology", "design"]
}
]
I need to select all videos with the tag "business" in chapterId 1.
Can this be done without changing the structure of my collection ?

You should use aggregation so below query will help you
db.collectionName.aggregate(
{"$unwind":"$videos"},
{"$match":{"chapterId":1,"videos.tags":"business"}}
)

Related

How to iterate a mongo db document and update a nested array

I need to remove entries inside a 2d array of documents structure in mongodb.
Sample is as below
{
"_id" : ObjectId("5ffef283f1f06ff8524aa2c2"),
"applicationName" : "TestApp",
"pName" : "",
"environments" : [],
"stages" : [],
"createdAt" : ISODate("2021-01-15T09:51:35.546Z"),
"workflows" : [
[
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
},
{
"pName" : "Test2",
"wName" : "TestApp_Test2",
"agent" : ""
}
],
[
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
}
]
],
"updatedAt" : Date(-62135596800000)
}
So, I want to remove all document occurences of
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
}
from both the arrays.
pName:Test1 can be used to filter it out.
What's the query which can be used to find this and delete it ?
I am ok to do a find and then iterate over the collection , find the matching entry and then update the document. I have to do this using Go mongodb driver
Since this is kind of complex for me as I am new to both golang and mongo db, I am stuck.
Update:
1.Tried {$pull: {workflows: {pName:"Test1"}}}, {multi: true} in the update() call as suggested but didn't work.
2.Tried something like this
db.getCollection('workflows').update({_id:ObjectId('5ffef283f1f06ff8524aa2c2')}, {$pull:{workflows: { $elemMatch: {pName:'Test2'}}}} )
This is removing the entire array as shown below because Test2 is present in that. I need to remove only the Test2 document
[
{
"pName" : "Test1",
"wName" : "TestApp_Test1",
"agent" : ""
},
{
"pName" : "Test2",
"wName" : "TestApp_Test2",
"agent" : ""
}
]
I'll give you a hint as you are new and you haven't posted the tried things.
You could use $pull to remove documents matching the conditions.
similar example
And you could use official mongodb driver for go or most used gopkg
An example SO post

MongoDB get all embedded documents where condition is met

I did this in my mongodb:
db.teams.insert({name:"Alpha team",employees:[{name:"john"},{name:"david"}]});
db.teams.insert({name:"True team",employees:[{name:"oliver"},{name:"sam"}]});
db.teams.insert({name:"Blue team",employees:[{name:"jane"},{name:"raji"}]});
db.teams.find({"employees.name":/.*o.*/});
But what I got was:
{ "_id" : ObjectId("5ddf3ca83c182cc5354a15dd"), "name" : "Alpha team", "employees" : [ { "name" : "john" }, { "name" : "david" } ] }
{ "_id" : ObjectId("5ddf3ca93c182cc5354a15de"), "name" : "True team", "employees" : [ { "name" : "oliver" }, { "name" : "sam" } ] }
But what I really want is
[{"name":"john"},{"name":"oliver"}]
I'm having a hard time finding examples of this without using some kind of programmatic iterator/loop. Or examples I find return the parent document, which means I'd have to parse out the embedded array employees and do some kind of UNION statement?
Eg.
How to get embedded document in mongodb?
Retrieve only the queried element in an object array in MongoDB collection
Can someone point me in the right direction?
Please add projections to filter out the fields you don't need. Please refer the project link mongodb projections
Your find query should be constructed with the projection parameters like below:
db.teams.find({"employees.name":/.*o.*/}, {_id:0, "employees.name": 1});
This will return you:
[{"name":"john"},{"name":"oliver"}]
Can be solved with a simple aggregation pipeline.
db.teams.aggregate([
{$unwind : "$employees"},
{$match : {"employees.name":/.*o.*/}},
])
EDIT:
OP Wants to skip the parent fields. Modified query:
db.teams.aggregate([
{$unwind : "$employees"},
{$match : {"employees.name":/.*o.*/}},
{$project : {"name":"$employees.name",_id:0}}
])
Output:
{ "name" : "john" }
{ "name" : "oliver" }

mongodb extracting values from array

Following is example of table in mongodb, I have multiple records for companies like this, which I need help with.
I wanted to query the below table wherein using value from company I should be able to retrieve the name of all the cars.
"vehicles" : [
{
"source" : "jeep",
"tag" : [
{
"company" : "toyota",
"name" : "fortuner"
},
{
"company" : "rangerover",
"name" : "discovery"
]
}
]
Thanks...
try this :
db.vehicles.find({tag: {$elemMatch: {company:'toyota'}}}).pretty();
read more here : https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

Get specific object in array of array in MongoDB

I need get a specific object in array of array in MongoDB.
I need get only the task object = [_id = ObjectId("543429a2cb38b1d83c3ff2c2")].
My document (projects):
{
"_id" : ObjectId("543428c2cb38b1d83c3ff2bd"),
"name" : "new project",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b"),
"members" : [
ObjectId("5424ac37eb0ea85d4c921f8b")
],
"US" : [
{
"_id" : ObjectId("5434297fcb38b1d83c3ff2c0"),
"name" : "Test Story",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b"),
"tasks" : [
{
"_id" : ObjectId("54342987cb38b1d83c3ff2c1"),
"name" : "teste3",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
},
{
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
]
}
]
}
Result expected:
{
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
But i not getting it.
I still testing with no success:
db.projects.find({
"US.tasks._id" : ObjectId("543429a2cb38b1d83c3ff2c2")
}, { "US.tasks.$" : 1 })
I tryed with $elemMatch too, but return nothing.
db.projects.find({
"US" : {
"tasks" : {
$elemMatch : {
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2")
}
}
}
})
Can i get ONLY my result expected using find()? If not, what and how use?
Thanks!
You will need an aggregation for that:
db.projects.aggregate([{$unwind:"$US"},
{$unwind:"$US.tasks"},
{$match:{"US.tasks._id":ObjectId("543429a2cb38b1d83c3ff2c2")}},
{$project:{_id:0,"task":"$US.tasks"}}])
should return
{ task : {
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
Explanation:
$unwind creates a new (virtual) document for each array element
$match is the query part of your find
$project is similar as to project part in find i.e. it specifies the fields you want to get in the results
You might want to add a second $match before the $unwind if you know the document you are searching (look at performance metrics).
Edit: added a second $unwind since US is an array.
Don't know what you are doing (so realy can't tell and just sugesting) but you might want to examine if your schema (and mongodb) is ideal for your task because the document looks just like denormalized relational data probably a relational database would be better for you.

Query MongoDB N-Tier Nested on every Level

I've got this structure of document, saved in MongoDB 2.6.1, running on Linux:
{
"_id" : "1",
"name" : "Level0",
"childs" : [
{
"id" : "2",
"name" : "Level1",
"childs" : [
{
"id" : "3",
"name" : "Level2",
"childs" : [
{
"id" : "4",
"name" : "Level3-1",
},
{
"id" : "5",
"name" : "Level3-2",
}
]
}
...
Every Element got his childs and every child-element got his own childs until the technical end.
Now I want to Query my MongoDB with something like:
db.categories.find({'childs':{$elemMatch:{$all:['Level19-23']}}})
This Query dont work by the way.
What is a good query to get my elements?
I dont know anything about the children or parents, I've got only the name of the element, and I need the element with all his children.
Anyone got an advise for me, the MongoDB Newbe? :)
Thanks in advance!