0

I am looking for a way - and dont even now if this is possible - just to return a part of a list saved in mongodb.

Lets have a look in my currently document:

{
    _id : 'MyId',
    name : 'a string',
    conversations : [
        {
            user : 'Mike',
            input : 'Some input'
        },
        {
            user : 'Stephano',
            input : 'some other input'
        }
    ]

}

What I now want to do is smth like this:

var myOutput;
myOutput = db.my_collection.find(
{
    _id : 'MyId',
    'conversations.user' : 'Mike'
}, {
    _id : 1,
    name : 1,
    conversations : {
        $where : {
            user : 'Mike'
        }
    }
});

Goal is it just to get back the conversation array item where user has the value Mike.

Is this still possible in MongoDB ? didn't found any reference in the documentation for the field limitations in mongoDB.

styvane
  • 59,869
  • 19
  • 150
  • 156
TJR
  • 6,307
  • 10
  • 38
  • 64
  • the Mongodb documentation has multiple examples on how to use find. Some are similar to what you need, http://docs.mongodb.org/manual/reference/method/db.collection.find/ – faljbour Feb 21 '15 at 19:12
  • I dont need a find example - how to find a document where this user is set is in my example - I need a way to limitate the returned value (just return a part of the array) – TJR Feb 21 '15 at 19:14

2 Answers2

2

Use the $ positional operator in a projection:

> db.my_collection.find({ "_id" : "MyId", "conversations.user" : "Mike" },
                      { "_id" : 1, "name" : 1, "conversations.$" : 1 })
{
    "_id" : 'MyId',
    "name" : 'a string',
    "conversations" : [
        { "user" : 'Mike', "input" : 'Some input' }
    ]
}

This projects only first matching array element.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23
1

Are you aware of the aggregation pipeline?

db.my_collection.aggregate([
    { "$match": { "_id": "MyId"}}, { "$unwind": "$conversations"}, 
    { "$match": {"conversations.user": "Mike"}}
])

Output

{ 
    "_id" : "MyId", 
    "name" : "a string", 
    "conversations" : 
    { 
        "user" : "Mike", 
        "input" : "Some input" 
    } 
}
styvane
  • 59,869
  • 19
  • 150
  • 156