I have documents in mongodb that i'm accessing with mongoid that looks like this:
{
"first_name": "Clarke",
"last_name": "Kent",
"vault_info": {
"container": "names",
"created_at": "2013-12-09T23:18:07.963Z",
"updated_at": "2013-12-09T23:18:07.963Z",
"vault_id": "4dc08baa97"
}
}
I want to be able to query for it using the for_js method like this:
Model.for_js('this.vault_info.vault_id=="5088de6f12"')
If there is a single document in the database this works. If there is more than one it gives this error:
"TypeError: Cannot read property 'vault_id' of undefined near '==\"5088de6f12\"' "
Any help would be appreciated.
Robert
It looks like the new documents you're adding don't have a vault_info property on them. That means that this.vault_info evaluates to undefined, and you can't access any property (including vault_id) of undefined.
If you don't have to use the for_js method, just use the where method like this:
Model.where('vault_info.vault_id' => '5088de6f12')
Mongo intelligently filters out all documents that lack the vault_info property, so you don't get any errors about accessing properties of undefined. JavaScript doesn't help you out like that, so if you do absolutely have to use the for_js method, you'll have to check each step of the way. That'd look something like:
Model.for_js('this.vault_info && this.vault_info.vault_id=="5088de6f12"')
I'd encourage you to use the where method, though. The less JavaScript you send to MongoDB the better.
Related
I'm working on a Raspberry Pi project that collects weather measurements and stores them in a Mongo database like this:
{
"_id": {
"$oid": "577975c874fece5775117209"
},
"timestamp": {
"$date": "2016-07-03T20:30:00.995Z"
},
"temp_f": 68.9,
"temp_c": 20.5,
"humidity": 50,
"pressure": 29.5
}
The data is going into the Mongo db just fine. Next, I'm trying to build a Flask-based dashboard that enables me to look at the recorded data. On one of the pages of the dashboard, I want to show the current recorded values, so what I need to do is pull out the last measurement and pass it to a flask template for rendering to the browser.
I found a post here that said I could use:
data = db.measurements.find().limit(1).sort({"$natural": -1})
but natural doesn't seem to be a valid option for the call to find.
This works:
measurement = mongo.db.measurements.find_one()
It pulls back one random measurement that I can then pass to the flask template, but how do I use sort to get the most recent one?
I tried:
measurement = mongo.db.measurements.find_one().sort([("timestamp", -1)])
but that generates an attribute error: AttributeError: 'dict' object has no attribute 'sort'
I've also tried:
cursor = mongo.db.measurements.find().limit(1).sort({"timestamp": -1})
but that doesn't work either.
I'm missing something here, can someone give me a quick, complete fix for this?
It turns out Pymongo has a different format for sort. You can't pass in a JSON object, you have to use a dict. Once I fixed that, it all works:
cursor = mongo.db.measurements.find().sort([('timestamp', -1)]).limit(1)
I'm new to Meteor. I've been stuck on this problem for a while. I can successfully adds items to a collection and look at them fully in the console. However, I cannot access all of the read operations in my .js file.
That is, I can use .find() and .findOne() with empty parameters. But when I try to add .sort or an argument I get an error telling me the object is undefined.
Autopublish is turned on, so I'm not sure what the problem is. These calls are being made directly in the client.
This returns something--
Template.showcards.events({
"click .play-card": function () {
alert(Rounds.find());
}
})
And this returns nothing--
Template.showcards.events({
"click .play-card": function () {
alert(Rounds.find().sort({player1: -1}));
}
})
Sorry for the newbie question. Thanks in advance.
Meteor's collection API works a bit differently from the mongo shell's API, which is understandably confusing for new users. You'll need to do this:
Template.showcards.events({
'click .play-card': function() {
var sortedCards = Rounds.find({}, {sort: {player1: -1}}).fetch();
console.log(sortedCards);
}
});
See this for more details. Also note that logging a cursor (the result of a find) probably isn't what you want. If you want to see the contents of the documents, you need to fetch them.
Rounds.find().sort({player1: -1}) returns a cursor, so you will want to do this:
Rounds.find().sort({player1: -1}).fetch();
Note that this returns an Array of document objects. So you would do something more like this:
docs = Rounds.find().sort({player1: -1}).fetch();
alert(docs[0]);
I am using below query to fetch data from mongo-db:
db.FetchedUrl.aggregate({
"$match": {
"type": db.eval('echoFunction(\"news\")')
}
})
This is my stored function:
db.system.js.save({
_id: "echoFunction",
"value": function(x){return x}
})
This code is working fine at mongo-db shell. How to write equivalent Java code to call stored function in aggregation?
I think you need to understand what is actually happening here. Take this for an example, and you can do it yourself in the shell. So declare a variable there like this:
var param = db.eval('echoFunction(\"news\")');
And then do the aggregate again like this:
db.FetchedUrl.aggregate({
"$match": {
"type": param
}
})
Here is the thing. You know you don't have a "stored" variable on your server called "param" but of course the result is the same as what you did before.
This is because, much as the same as what you have done, this value gets evaluated in the "shell" before the request is sent to the server.
So in this case, your "server side" function is not providing any server side evaluation at the time of the aggregate being performed.
What this means is that any "Java" code you write is going to be pre-evaluated into the BSON document that is sent before it is sent to the server.
So whatever means you are using to "fetch" this value, then you need to write that in "Java" code. That value is then placed in as the value to the same key in a BSON document by the methods your driver supplies.
There are some notes on aggregation with the Java driver on the MongoDB website.
I started using couchbase,
i like it a lot but one thing i cant find,
making a dynamic query,
{
"sender_name": "roman",
"sender_id": 123,
"content": "Hello World"
}
Now i want to query for document where "sender_id" = ?.
It can be any number,
Regular view with doc and meta cant help me because i dont know the value,
I should expect any sender_id.
Hope you can help me, thanks alot.
Ok , with Couchbase you can write Map&Reduce functions, and create views. The map functions accept parameters. I am not quite familiar with writing a Map function, but from couchbase.com I think this map function will do your job.
function(doc, meta)
{
emit(doc.sender_id, [doc.content]);
}
And your query would be ?key=["123"]
Go through these links
http://hardlifeofapo.com/creating-an-e-commerce-platform-using-couchbase-2/
http://hardlifeofapo.com/basic-couchbase-querying-for-sql-people/
http://www.couchbase.com/docs/couchbase-manual-2.0/couchbase-views-writing-sql-where.html
I have an app using Mongoid on top of MongoDB and an update is failing silently.
The code looks like this:
# Are we getting a new attribute? Yes we are!
p "attr first name = #{#attributes['first_name']}"
if user.update_attributes!(#attributes)
u = User.find(params[:id]).to_json
end
No exception is thrown in this code. So I looked at my MongoDB log and constructed this query based on what mongo is trying to do:
db.users.update({ "_id": "4d5561276ce886c496000001" }, { $set: { "first_name": "Erinamodobo" } }, false);
Now this does not cause any exceptions but when I grab the record that was supposed to be updated with this query:
db.users.find({"email":"escharling#somecompany.com"})
I see that the "first_name" attribute has not been updated.
Any idea why this could be happening? Sounds like something stupid.
Thanks!
You need to find out what
user.update_attributes!(#attributes)
is actually doing. This could be an issue with Mongoid. When you configure Mongoid, you can set up a logger. There you should be able to see what the driver is writing to MongoDB, and that should help answer your question. The next best thing is to post your code to the Mongoid mailing list (http://groups.google.com/group/mongoid) where people who work with Mongoid all the time will probably know what's going on.
Updating Mongoid to the latest rc.7 fixed this issue
Enable "safe mode" on your operations.