Pregunta

I'm trying to write some restful web API's, I have a collection called as community, and it has some 10 fields. But In my GetCommunityAPI call I only want to pass on the necessary Information to the mobile device.

I've referred to this blog example, this has suggested the following MongoDB query

$db->users->find({}, {username => 1});

I've written my Mongoid Search as

@result=@result.find({},{:username=>1})

But this gives me an Error that it is not able to find a valid document with id = {}

I've also tried

@result=@result.only({:username=>1})

But instead of returning only username it returns everything making the other field as null.

{"_id":"534186e5414fc34bc5000002","ad":null,"ae":null,"cat":null...and so on}

My question is, in order to make the API calls most efficient. consuming the least amount to mobile data is it possible to send fetch the data from MongoDB in the following format

{"_id":"534186e5414fc34bc5000002"}

This approach would make all my API's sending only valid information, and be mobile network friendly. As i'm expecting some 1000's of object in a single API call.

Also is it possible to get my output in this format ?

[{"_id":"534186e5414fc34bc5000002","un":"Name"},{"_id":"534186e5414fc34bc500000‌​3","un":"Dummy"}]
¿Fue útil?

Solución

Using mongo itself, it will return null values. Have you tried using the pluck method in mongoid 3 ?

Collection.all.pluck(:username)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top