2

My mongodb database looks like this.

[{
    "_id": ObjectId("5e049ebc8e935c407f78c190"),
    "2020-04-25": [
      {
        "browser": "Chrome",
        "ts": "2020-04-25 21:05"
      },
      {
        "browser": "Firefox",
        "ts": "2020-04-25 21:05"
      }
    ]
  },
  {
    "_id": ObjectId("5e049ebc8e935c407f68c190"),
    "2020-04-26": [
      {
        "browser": "Chrome",
        "ts": "2020-04-26 10:45"
      },
      {
        "browser": "Edge",
        "ts": "2020-04-26 10:45"
      },
      {
        "browser": "Firefox",
        "ts": "2020-04-26 10:46"
      }
    ]
  }]

I want to find all distinct values of key browser.

I tried using distinct but i'm stuck on how to use it for all dates in the db.

I tried $all operator but found out it can be only used for values not the key.

1 Answer 1

1

With the current data structure there's no way avoiding using $objectToArray on all the data and then grouping. which will make this pipeline very inefficient.

db.collection.aggregate([
    {
        "$addFields": {
            "newField": {
                "$objectToArray": "$$ROOT"
            }
        }
    },
    {
        "$unwind": "$newField"
    },
    {
        "$unwind": "$newField.v"
    },
    {
        "$group": {
            "_id": "$newField.v.browser"
        }
    },
    {
        "$match": {
            // this null is due to the _id field, you could also filter "newField" before unwinding instead.
            "_id": {"$ne": null}
        }
    }
]);

With that said I recommend you consider re-structuring your data, With some like:

{
    "_id": ObjectId("5e049ebc8e935c407f68c190"),
    date: "2020-04-26",
    data: [
        {
            "browser": "Chrome",
            "ts": "2020-04-26 10:45"
        },
        {
            "browser": "Edge",
            "ts": "2020-04-26 10:45"
        },
        {
            "browser": "Firefox",
            "ts": "2020-04-26 10:46"
        }
    ]
}

Now you can easily achieve the same result (and many others) like so :

db.collection.distinct("data.browser")
Sign up to request clarification or add additional context in comments.

Comments

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.