Anuj Panchal
Anuj Panchal

Reputation: 415

How to add a custom field using mongo aggregation?

Structure of a document in my collection is as follows:

{
    "tracking": [
        {
            "track_id": "abcd",
            "track_name": "Sample track"
        }, {...}, ...
    ]
}

I have multiple such objects in an array called tracking. Now I am trying to add a field called current_status using mongo aggregation as follows:

        {
            "$addFields": {
                "current_status": {
                    "$cond": {
                        "if": {"tracking.track_id": {"$in": ['abcd']}},
                        "then": "Approved",
                        "else": "Pending"
                    }
                }
            }
        }

After running this, I am getting the following error:

pymongo.errors.OperationFailure: Invalid $addFields :: caused by :: FieldPath field names may not contain '.'.

I want to add a new field in the result of my Mongo aggregation query on the basis of whether an object with track_id abcd is present or not in the tracking array.

Upvotes: 1

Views: 1062

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Try this:

db.collection.aggregate([
    {
        "$addFields": {
            "tracking": {
                "$map": {
                    "input": "$tracking",
                    "as": "item",
                    "in": {
                        "$cond": {
                            "if": { "$eq": ["$$item.track_id", "abcd"] },
                            "then": {
                                "track_id": "$$item.track_id",
                                "track_name": "$$item.track_name",
                                "current_status": "Approved"
                            },
                            "else": {
                                "track_id": "$$item.track_id",
                                "track_name": "$$item.track_name",
                                "current_status": "Pending"
                            }
                        }
                    }
                }
            }
        }
    }
])

Output:

{
    "_id" : ObjectId("604f50859ee8b82dd8cd9f4a"),
    "tracking" : [
        {
            "track_id" : "abcd",
            "track_name" : "Sample track 1",
            "current_status" : "Approved"
        },
        {
            "track_id" : "fdsdf",
            "track_name" : "Sample track 2",
            "current_status" : "Pending"
        }
    ]
}

Upvotes: 1

Related Questions