Ryo
Ryo

Reputation: 1035

MongoDB - Return specifice field (not include hierarchy)

I have some data store in MongoDB :

{
        "_id" : ObjectId("52983ff67dbf497a8bb0192b"),
        "data" : [
                {
                        "LoadPct" : 10,
                        "RECORD_SEQ" : 1
                }
        ]
}
{
        "_id" : ObjectId("5298400b7dbf497a8bb0192d"),
        "data" : [
                {
                        "LoadPct" : 59,
                        "RECORD_SEQ" : 2
                }
        ]
}
{
        "_id" : ObjectId("529840217dbf497a8bb01934"),
        "data" : [
                {
                        "LoadPct" : 8,
                        "RECORD_SEQ" : 3
                }
        ]
}

Now i want a query will return data with customize format ,something like

_id                                   LoadPct
ObjectId("52983ff67dbf497a8bb0192b")  10
ObjectId("5298400b7dbf497a8bb0192d")  59
ObjectId("529840217dbf497a8bb01934")  8

Is this possible ?

//Update : I tried using Aggregate but error orccured :

> db.data.aggregate( {$match:{'data.LoadPct':{$gt:5}}}, {$group:{'_id':"_id",'data':'data.LoadPct'}} )
Error: Printing Stack Trace
    at printStackTrace (src/mongo/shell/utils.js:37:15)
    at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
    at (shell):1:24
Mon Dec 16 14:44:27.208 JavaScript execution failed: aggregate failed: {
        "errmsg" : "exception: the group aggregate field 'data' must be defined as an expression inside an object",
        "code" : 15951,
        "ok" : 0
} at src/mongo/shell/collection.js:L898

What's wrong ?

Upvotes: 2

Views: 6440

Answers (2)

Mzzl
Mzzl

Reputation: 4136

Are you sure you need an aggregation here? It looks like a simple find would return the data you want, though not exactly in the same shape:

db.data.find( {"data.LoadPct" : {"$gt" : 10}}, {"data.LoadPct" : 1} )

By the way, is 'data' really intended to be an array of one document with two key : value pairs? In the sample code for your aggregation, I think you forgot the $ where you're asking for the values of fields.

The error message you see means that you asked mongodb to aggregate by the field 'data', but didn't specify an operation to aggregate it by.

Compare it with the following in SQL:

# select a, b from foo group by a;
ERROR:  column "foo.b" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select a, b from foo group by a;

As opposed to:

# select a, max(b) from foo group by a;
 a  | max 
----+-----
 bb |   7
 aa |   9

This sort of does what you ask:

query = [
    {"$match":{"data.LoadPct":{"$gt":5}}}, 
    {"$unwind":"$data"}, 
    {"$project" : {"data" : "$data.LoadPct"}}, 
    {"$group" : {"_id" : "$_id", "data" : {"$first" : "$data"}}}
]

db.data.aggregate(query)

Upvotes: 1

rubenfa
rubenfa

Reputation: 851

You need to use an aggregate query and $unwind pipeline. Check MongoDB documentation

Upvotes: 1

Related Questions