1

I have following Json structure-

[{
 cName:"A",
"datastores" : [ 
    {
        "status":"unused"
    }, 
    {
        "name" : "datastore1",
         "status":"used"
    }, 
    {
        "name" : "onNetApp7m",
         "status":"used"
    }, 
    {
        "name" : "datastore1",
         "status":"used"
    }
    ],
},
{
 cName:"B",
"datastores" : [ 
    {
        "name" : "dsn",
         "status":"used"
    }, 
    {
        "name" : "dsn",
         "status":"used"
    }, 
    {
        "name" : "datastore2",
         "status":"used"
    }
    ],
}
]

I want to find only such names from array/list "ds" whose count is greater than 1. I want following output-

[{
"cName":"A",
"name" : "datastore1",
"count": 2
},
{
"cName":"B",
"name" : "dsn",
"count": 2
}]

Currently, for getting count, I am handling it in my code logic. Is it possible to get count from query itself using mongo??

2
  • ds has been changed to datastores - was it a typo? Commented Dec 5, 2014 at 8:41
  • @BatScream yes it is.. Commented Dec 5, 2014 at 8:52

1 Answer 1

1

You need to aggregate as below:

  • Unwind the datastores array.
  • Group the records by the cName and the datastores name fields. Get the count of records in each group.
  • The group we need to match is now the group having count > 1.
  • Project the required fields.

Code:

db.collection.aggregate([
{$unwind:"$datastores"},
{$group:{"_id":{"cName":"$cName","name":"$datastores.name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"_id":0,"cName":"$_id.cName","name":"$_id.name","count":1}}
])
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.