'index of an of array with objects [duplicate]
Input Doc:
/* 1 */
{
"_id" : ObjectId("6237e2103cd4b19dce804712"),
"userId" : "2701",
"shapes" : [
{
"shape" : "square",
"color" : "blue",
"completed" : true
},
{
"shape" : "circle",
"color" : "red",
"name" : "thisisred",
"completed" : false
},
{
"shape" : "rectangle",
"color" : "red",
"name" : "thisisred",
"completed" : false
}
]
}
How to find the indexes of Shape where color is red.
Ouput should contain:
Shapes:[1,2] // color red appears in 1st and 2nd indexed objects.
Solution 1:[1]
Use $unwind wtih includeArrayIndex
db.collection.aggregate([
{
$match: { "shapes.color": "red" }
},
{
$unwind: {
path: "$shapes",
includeArrayIndex: "index"
}
},
{
$match: { "shapes.color": "red" }
},
{
$group: {
_id: "$shapes.color",
Shapes: { $push: "$index" }
}
}
])
Solution 2, without unwind
db.collection.aggregate([
{
$match: { "shapes.color": "red" }
},
{
$set: {
shapes: {
$map: {
input: { $range: [ 0, { $size: "$shapes" } ] },
as: "s",
in: {
$mergeObjects: [
{ $arrayElemAt: [ "$shapes", "$$s" ] },
{ index: "$$s" }
]
}
}
}
}
},
{
$set: {
shapes: {
$filter: {
input: "$shapes",
as: "s",
cond: { $eq: [ "$$s.color", "red" ] }
}
}
}
},
{
$set: {
shapes: {
$map: {
input: "$shapes",
as: "s",
in: "$$s.index"
}
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
