I am new in mongodb/
I need to get a document using mongo shell if its first emdedded document, which matches condition A, mathes codition B.
For examle, I have only one doc in collection:
{
"_id": "life",
"docs": [{
"_id": "sex",
"p": 2,
"c": 2
}, {
"_id": "drugs",
"p": 1,
"c ": 2
}, {
"_id": "rock'n'roll",
"p": 1,
"c": 4
}]
}
If A condition is p=1, then
---- if B condition is с=2, I get "life" (embedded doc "drugs" matches the condtitions)
---- if B condition is c=4, I get empty result.
If A condition is c=2, then
---- if B condition is p=2, I get "life" (emdedded doc "sex" matches the conditions)
---- if B condition is p=1, I get empty result (
Tnx
Added:
The task is to filter the collection and get whole documents according to condtitions applied to emdedded document in specific way, so the question is not a duplicate I think.
But with help of that question I got the solution:
db.test.aggregation([
{
$project:
{
docs:
{
$filter:
{
input:"$docs",
as:"doc",
cond:{$eq:['$$doc.p',1]}
}
}
}
},
{
$project:
{
docs:{$slice:["$docs",1]}
}
},
{
$project:
{
docs:
{
$filter:
{
input:"$docs",
as:"doc",
cond:{$eq:['$$doc.c',2]}
}
}
}
},
{
$project:
{
"docs":1,
"n":{"$size":"$docs"}
}
},
{
$match:{"n":{$gt:0}}
}])
Another solution:
db.c.aggregate([
{
$project:
{
docs:
{
$filter:
{
input:"$docs",
as:"doc",
cond:{$eq:['$$doc.p',1]}
}
}
},
},
{
"$unwind":"$docs"
},
{
"$group":
{
"_id": "$_id",
"doc": { "$first": "$docs" }
}
},
{
$match:{"doc.c":2}
}])