質問

I have a very simple document:

{
    "_id" : ObjectId("5347ff73e4b0e4fcbbb7886b"),
    "userName" : "ztolley",
    "firstName" : "Zac",
    "lastName" : "Tolley"
    "data" : {
        "temperature" : [
            {
                "celsius" : 22,
                "timestamp" : 1212140000
            }
        ]
    }
}

I want to find a way to write a query that searches for userName = 'ztolley' and only returns back the last 10 temperature readings. I've been able to say just return the data field but I couldn't find a way to say just return data.temperature (there are many different data properties).

When I tried

db.user.find({userName:'ztolley'},{data: {temperature: {$slice: -10}}})

I got unsupported projection.

役に立ちましたか?

解決

I'd try using the Aggregation framework http://docs.mongodb.org/manual/aggregation/ .

Using your schema this should work:

db.user.aggregate([{$match:{"userName":"ztolley"}},{$unwind:"$data.temperature"},{$sort:{"data.temperature.timestamp":-1}},{$limit:10}, {$project:{"data.temperature":1, _id:0}}])

It returns the temperature readings for that user, in reverse sorted order by timestamp, limited to 10.

他のヒント

It looks you write wrong projection, try it with dot '.' notation:

db.user.find( { userName:'ztolley' },{ 'data.temperature': { $slice: -10 } } );
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top