Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb serialize subset result

I have this simple db, with subset of elements:

{ "_id" : ObjectId("5019eb2356d80cd005000000"),
    "photo" : "/pub/photos/file1.jpg",
    "comments" : [
        {
            "name" : "mike",
            "message" : "hello to all"
        },
        {
            "name" : "pedro",
            "message" : "hola a todos"
        }
    ]
},
{ "_id" : ObjectId("5019eb4756d80cd005000001"),
    "photo" : "/pub/photos/file2.jpg",
    "comments" : [
        {
            "name" : "luca",
            "message" : "ciao a tutti"
        },
        {
            "name" : "stef",
            "message" : "todos bien"
        },
        {
            "name" : "joice",
            "message" : "vamos a las playa"
        }
    ]
}

when I execute a subset find: db.photos.find({},{"comments.name":1})

Im receive this structure:

[
    {
        "_id" : ObjectId("5019eb2356d80cd005000000"),
        "comments" : [
            {
                "name" : "mike"
            },
            {
                "name" : "pedro"
            }
        ]
    },
    {
        "_id" : ObjectId("5019eb4756d80cd005000001"),
        "comments" : [
            {
                "name" : "luca"
            },
            {
                "name" : "stef"
            },
            {
                "name" : "joice"
            }
        ]
    }
]

But I want to get a simple one-dimensional array, like this(or similar):

[
    {
        "name" : "mike"
    },
    {
        "name" : "pedro"
    },
    {
        "name" : "luca"
    },
    {
        "name" : "stef"
    },
    {
        "name" : "joice"
    }
]

I need to implement this query with mongo php official driver, but the language is not important, I just want to understand by what logic can I accomplish this by mongo shell

tnk!

like image 884
stefcud Avatar asked Feb 23 '26 07:02

stefcud


1 Answers

The easiest option would be to use distinct():

>db.photos.distinct("comments.name");
[ "mike", "pedro", "joice", "luca", "stef" ]

Here's another example using JavaScript:

// Array to save results
> var names = []

// Find comments and save names
> db.photos.find({},{"comments.name":1}).forEach(
          function(doc) { doc.comments.forEach(
              function(comment) {names.push(comment.name)})
          })

// Check the results
> names
[ "mike", "pedro", "luca", "stef", "joice" ]

Here's an example using the new aggregation framework in the upcoming MongoDB 2.2:

db.photos.aggregate(
  { $unwind : "$comments" },
  { $group : {
     _id: "names",
     names: { $addToSet : "$comments.name" }
  }},
  { $project : {
     '_id' : 0,
     'names' : 1,
  }}
)
like image 93
Stennie Avatar answered Feb 24 '26 23:02

Stennie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!