3

Eg:- Following is a sample document in a collection 'clubs',

Sample document

{
    "_id" : ObjectId("5cb8218ce2911e7c707e27fa"),
    "name" : "name 1",
    "members" : {
        "user_1" : {
            "created" : ISODate("2019-04-18T07:04:44.748Z"),
            "lastActive" : 1555584757282,
            "state" : 1,
            "unreadMessages" : 0,
            "userId" : "user_1_id"
        },
        "user_2" : {
            "lastActive" : 1555588409686,
            "state" : 1,
            "unreadMessages" : 0,
            "userId" : "user_2_id"
        }
    }
}

Mongo DB query should return the following fields :-

Desired Output-

{
    {
        "_id" : ObjectId("5cb8218ce2911e7c707e27fa"),
        "name" : "name 1",
        "members" : {
            "user_1" : {
                "lastActive" : 1555584757282
            },
            "user_2" : {
                "lastActive" : 1555588409686
            }
         }
    }
}

1 Answer 1

1

You can use below aggregation

db.collection.aggregate([
  { "$addFields": {
    "members": {
      "$arrayToObject": {
        "$map": {
          "input": { "$objectToArray": "$members" },
          "in": {
            "k": "$$this.k",
            "v": { "lastActive": "$$this.v.lastActive" }
          }
        }
      }
    }
  }}
])

Example

Sign up to request clarification or add additional context in comments.

1 Comment

The username in members object can be different in each document. I need to write a query to find the lastActive timestamp in all the documents for all the different users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.