1

I'm just wondering if it's possible to run a query to grab only a partial of a certain field based on a condition. For example my data set looks like:

"Name":"John",
"History":[ 
    {
        "speed" : 5,
        "type" : "walking"
    }, 
    {
        "speed" : 6,
        "type" : "walking"
    }, 
    {
        "speed" : 7,
        "type" : "walking"
    }
]

I want to run a query like:

db.getCollection('membermodel').find({
    "Name":"John"
}, {
    "Name":"1",
    "History":"1",
    //specify field condition here 
    "History.speed":{$gt:6}
});

will give me a result only containing the data which its speed is greater than 6:

"Name":"John",
"History":[ 
    {
        "speed" : 7,
        "type" : "walking"
    }
]

Thank you very much in advance. Mars

Mars Zhu
  • 296
  • 2
  • 13
  • yes, it is possible. Was this question? – Abie Sep 09 '15 at 08:25
  • great! Can you please let me know which commend shall I use? I've been reading the documentation for a few hours now:( Thank you! – Mars Zhu Sep 09 '15 at 08:29
  • You have the gt in the wrong place. Should be something like - "Name":"John", History : {$eleMatch : speed..... – gpullen Sep 09 '15 at 08:29
  • 3
    possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection). See the `$elemMatch` or positional `$` examples for a single match and the `.aggregate()` examples for multiple matches. – Blakes Seven Sep 09 '15 at 08:41
  • @gpullen Thank you for your reply. That still return the full History array, I just want to return a partial set of "History" – Mars Zhu Sep 09 '15 at 08:45

2 Answers2

3
db.getCollection('test').find({"Name":"John"},{"Name":1, "History":{$elemMatch :{"speed":{$gt:6}}}});

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

elp
  • 8,021
  • 7
  • 61
  • 120
TharunRaja
  • 707
  • 7
  • 28
0

For partial result use below query:

db.getCollection('test').find({"History.speed":7},{_id: 0, 'History.type.$': 1})

This will give only those History objects which will pass your criterion.

Abie
  • 624
  • 5
  • 12
  • Criteria looks wrong here as compared to the question asked by the OP as this will only match things where the value is "exactly" 7. Also there is a marked duplicate here long before your reply, which contains only "one" of the many possible answers listed there. – Blakes Seven Sep 09 '15 at 09:11