Reputation: 23
I've installed MongoDB and started testing it. I am new to MongoDB and trying to learn it. I have created a collection with the following items:
{ "_id" : ObjectId("5fb60945df88631311ab8a48"), "name" : "x-market", "tags" : ["water", "soda", "water"] }
{ "_id" : ObjectId("5fb60945df88631311ab8a49"), "name" : "y-market", "tags" : ["juice", "water"] }
What I'd like to do is query so I get, for each tag/document, 1 document having the name of the document and the tag with an array of indices of the tag in the tags array. It is complicated but the result should look like this:
{ "_id" : ObjectId, "name" : "x-market", "tag" : "water", index = [0,2]}
{ "_id" : ObjectId, "name" : "x-market", "tag" : "soda", index = [1]}
{ "_id" : ObjectId, "name" : "y-market", "tag" : "juice", index = [0]}
{ "_id" : ObjectId, "name" : "y-market", "tag" : "water", index = [1]}
How do I query for this? I tried to use $group, $project $reduce
operators but I got lost and my query is failing to execute. Any help would be appreciated, thank you!
Upvotes: 2
Views: 27
Reputation: 36114
You can try,
$unwind
deconstruct tags
array and add arrayindex in index
key$group
by name
and tags
, push index
in index array, get first name
$project
to show required fieldsdb.collection.aggregate([
{
$unwind: {
path: "$tags",
includeArrayIndex: "index"
}
},
{
$group: {
_id: {
_id: "$_id",
tags: "$tags"
},
name: { $first: "$name" },
index: { $push: "$index" }
}
},
{
$project: {
_id: "$_id._id",
name: "$name",
tag: "$_id.tags",
index: "$index"
}
}
])
Upvotes: 1