store mongodb result in array? - mongodb

Is it possible to store the result of a mongodb statement in array using jquery
I have like this
Polls_Coll.find({},{question:1});
I want all the question filed records to store in array some thing like
var arr[]=Polls_Coll.find({},{question:1});
I know above thing is wrong. I need something like that.
I need it for autocompletion. Now i'm taking source from one collection like this
source:_(Product_Mobiles.find().fetch()).pluck("title")
I want data from multiple sources and store it in array
Thanks

Using the mongo console you can do this with .toArray() like
var results = db.collection.find({}).toArray();
However, this might depend on the driver you are using... I guess the javascript driver has it as well.
If your problem is putting all the results from multiple sources into a single array:
How to merge two arrays in Javascript and de-duplicate items

You could merge the two arrays if thats what you mean:
var results = collection.find({}).fetch();
var results2 = collection2.find({}).fetch();
results = results.concat(results2);
Then you can do pluck
_(results).pluck("title");
Also you can't use db. in Meteor you have to use the name of the collection varaible you defined with new Meteor.Collection

Related

how to filter files in mongo Db

Am running 4.10 Mongo DB version
How to get the count of files filtered like
i have .doc and .pdf and .csv in file system in MOngo.
how to check the count of each format files (.csv ,.pdf,.doc)
Please let me know
I am assuming you don't mean references, but files that are in GridFS. In this case, the way it works is that Mongo simply puts them in 2 collections, one for files meta data, and another collection for chunks of files, that is to say the data of your files that is sliced in pieces. They are regular collections that you can query like any other collection. Their names are "fs.files" and "fs.chunks".
The one you want is "fs.files". For retrieving the files by type, you can use the field contentType. Here is how you get the number of PDFs:
db.fs.files.find({contentType: "application/pdf"}).count()
// or if your question is only for counting
db.fs.files.count({contentType: "application/pdf"})
Like I said, just like any other collection.
EDIT:
var pdfCount = db.fs.files.find({contentType: "application/pdf"}).count();
var csvCount = db.fs.files.find({contentType: "text/csv"}).count();
var docCount = db.fs.files.find({contentType: "application/msword"}).count();

Meteor Mongodb first object array not selectable with dot notation

I have tried and tried on Meteor and on Robomongo (Mongodb) to select objects with dot notation.
I would like to be able to filter team.0.wageringStats.wageringStraightSpread objects (sometimes subjects can be fields or arrays - thats another issue)
In the first image I can select team.wageringStats.wageringStraightSpread and get back all the subOjects of team (team has siblings not shown in images)
The second image I tried team.0.wageringStats.wageringStraightSpread and I get no fields.
Lastly i tried team.[0].wageringStats.wageringStraightSpread and
team[0].wageringStats.wageringStraightSpread and get the same result : 0 fields
I am at a loss and would like some help. Thank you
I am not sure what you are trying to do now? Because in your first command, you already have a list of team that match your criteria and then, put it into the loop of meteor to process. Why do you need to find only the first one ? By the way, in order to select the nth of the result set in mongodb, you will need something like skip and limit
db.collections.find({'team.wageringStats.wageringStraightSpread':1}).limit(1).skip(0)
(in skip, you need to pass the offset you need to reach to)
Also, if you only care about the first one, findOne is the one you need to do the query
db.collections.findOne({'team.wageringStats.wageringStraightSpread':1})
Be aware that the syntax of mongodb and meteor for querying is a bit different

Pymongo returns subdocs as dicts instead of SONs?

Is there a way to have pymongo return subdocs as SONs so they can be successfully passed back in for find queries? GridFS is returning the file._id as a dict instead of a SON; so, the subsequent call to grid_file.GridOut.read is failing to find the grid file. (I know, using dicts as _id is asking for trouble, but I'm dealing w/ an existing db/system.)
I don't see how I can intervene to coerce the file._id into the correctly ordered SON.
The MongoClient.document_class field controls this! Just add document_class=bson.son.SON, to the constructor

How can I return an array of mongodb objects in pymongo (without a cursor)? Can MapReduce do this?

I have a db set up in mongo that I'm accessing with pymongo.
I'd like to be able to pull a small set of fields into a list of dictionaries. So, something like what I get in the mongo shell when I type...
db.find({},{"variable1_of_interest":1, "variable2_of_interest":1}).limit(2).pretty()
I'd like a python statement like:
x = db.find({},{"variable1_of_interest":1, "variable2_of_interest":1})
where x is an array structure of some kind rather than a cursor---that is, instead of iterating, like:
data = []
x = db.find({},{"variable1_of_interest":1, "variable2_of_interest":1})
for i in x:
data.append(x)
Is it possible that I could use MapReduce to bring this into a one-liner? Something like
db.find({},{"variable1_of_interest":1, "variable2_of_interest":1}).map_reduce(mapper, reducer, "data")
I intend to output this dataset to R for some analysis, but I'd like concentrate the IO in Python.
You don't need to call mapReduce, you just turn the cursor into a list like so:
>>> data = list(col.find({},{"a":1,"b":1,"_id":0}).limit(2))
>>> data
[{u'a': 1.0, u'b': 2.0}, {u'a': 2.0, u'b': 3.0}]
where col is your db.collection object.
But caution with large/huge result cause every thing is loaded into memory.
What you can do is to call mapReduce in pymongo and pass it the find query as an argument, it could be like this:
db.yourcollection.Map_reduce(map_function, reduce_function,query='{}')
About the projections I think that you would need to do them in the reduce function since query only specify the selection criteria as it says in the mongo documentation
Building off of Asya's answer:
If you wanted a list of just one value in each entry as opposed to a list of objects--using a list comprehension worked for me.
I.e. if each object represents a user and the database stored their email, and you say wanted all the users that were 15 years old
user_emails = [user['email'] for user in db.people.find( {'age' : 15} )]
More here

Mongoid Query Syntax Question

I need to retrieve a set of answers according to 2 attributes.
This is what i want to do:
# where liker_ids is an array and user_id is a bson in the answer document
feed_answers=Answer.any_in(:liker_ids=>to_use,:user_id.in=>to_use).desc()map{|a|a}
What i ended up doing:
# to use
to_use=[some array of ids]
friend_answers=Answer.any_in(:liker_ids=>to_use).map{|a|a}
liked_answers=Answer.where(:user_id.in=>to_use).map{|a|a}
feed_answers=(friend_answers+ liked_answers).sort{|x,y| y.created_at<=>x.created_at}
The problem is that I do not not know how to combine the 2 queries into one. I have been trying out various combinations, but nothing seems to work. and my hacked together method is highly inefficient of course.
You should do(Missing parameter to desc):
Answer.any_in(:liker_ids=>to_use, :user_id.in=>to_use).desc(:created_at)
But the any_in here is not correctly used, it behaves similar to where in this situation. You probably want or:
Answer.or(:liker_ids=>to_use).or(:user_id.in=>to_use).desc(:created_at)
# or
Answer.any_of({:liker_ids=>to_use}, {:user_id.in=>to_use}).desc(:created_at)
# or
Answer.or({:liker_ids=>to_use}, {:user_id.in=>to_use}).desc(:created_at)
You don't need that map at the end of criteria chain, mongoid criteria are lazy loaded, when they encounter a method which criteria do not respond to. They can also leverage mongodb cursors, so it is advised not to use map if it is not necessary. You should use Criteia#only or Criteria#without if you want to retrieve subset of fields from mongodb.