user3142695
user3142695

Reputation: 17332

mongoDB: aggregate with incrementing field value

I need to convert a collection with nested documents to a model tree structure with parent references. The new documents should have a field with an incrementing value, which is starting from 1 for every document.

So this is how my structure looks like:

{
    "_id" : "sdaGREsfRdfGdFdwG",
    "docTitle" : "Document 1",
    "group" : [
        {
            "id" : "cdPhkTpMXi8z6TqMT"
            "title" : "title 1",
            "data" : [
                {
                    "id" : "Nkspf5kKfPo3axeJA",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                },
                {
                    "id" : "vyjgkuNXRN9KkCd5o",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                }
            ],

        },
        {
            "id" : "TuibXPe5qMvqdMW6q"
            "title" : "title 2",
            "data" : [
                {
                    "id" : "f5L5zsSNRSQKWoAXL",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                },
                {
                    "id" : "Ca8ncFgq83RoeD8he",
                    "some" : "data",
                    "other" : "things",
                    "and" : "so on",    
                },
            ],

        }
    ]
}

As you can see, there is a group array, which I want to convert into single documents:

{
    "_id" : "cdPhkTpMXi8z6TqMT"
    "title" : "title 1",
    "type" : "group",
    "order": 1,
    "parent" : "sdaGREsfRdfGdFdwG"
},
{
    "_id" : "TuibXPe5qMvqdMW6q"
    "title" : "title 2",
    "type" : "group",
    "order": 2,
    "parent" : "sdaGREsfRdfGdFdwG"
}

I do that with aggregate:

db.myCol.aggregate([{$unwind:"$group"}, 
    {$project:{_id:"$group.id", title:"$group.title", 
               parent:"$_id", type:{$literal:"group"}}},
    { $out : "target" }
]);

But I don't know how to set an order-field which has an incrementing value. And this incrementing value should be starting by 1 for every main document.

Upvotes: 2

Views: 4784

Answers (1)

Gor
Gor

Reputation: 2908

Well. Try using includeArrayIndex: "arrayIndex"

{
  $unwind:
  {
    path: <field path>,
    includeArrayIndex: <string>,
    preserveNullAndEmptyArrays: <boolean>
  }
}

Read more about $unwind here.

EDIT: Your example should be something like this

db.myCol.aggregate([
  {
    $unwind: { 
      path: "$group",
      includeArrayIndex: "arrayIndex"
    }
  }, 
  {
    $project: {
      _id: "$group.id",
      title: "$group.title",
      parent: "$_id",
      type: { $literal: "group" }
    }
  }
]);

Upvotes: 6

Related Questions