mongodb query mixing timestamps and ISODates - mongodb

I have a mongodb collection containing docs with both ISODates and timestamps in them, something like this:
doc = {
"_id" : ObjectId(...),
"updated" : 1445939778450,
"delivered" : ISODate("2016-12-21T09:40:29.082Z")
...
}
how can I compare updated and delivered fields using $where?

That's a great question! :)
It seems that mongodb handles this conversion automatically when using $where, so simply query like this:
db.my_collection.find({ $where : "this.updated > this.delivered" })
(if someone can point to documentation about this feature, please add)

Related

How do a query to find by Id using DBRef in MongoDB? [duplicate]

suppose I have the following datastructure:
var user = {_id: 'foo', age: 35};
var post = {_id: '...', author: {$ref: user, $id: 'foo'},...};
How can I query all posts which references user[foo]? I tried the following but not work:
db.post.find('author._id': 'foo');
var u = db.user.find({_id: 'foo'});
db.post.find('author': u);
neither can I find the answer from the official document and google!
Anyone has any idea?
Got it:
db.post.find({'author.$id': 'foo'})
This db.post.find('author.$id': 'foo') has missing the {}, so the correct sentence is:
db.post.find({'author.$id': 'foo'})
Also this can be achieved with:
db.post.find({'author': DBRef("user", ObjectId('foo'))})
But is more compact and practical the first way.
You can use the .$id reference but it will ignore any indexes on those fields.
I would suggest ignoring that method unless you are querying it directly via the terminal or want to look up something quickly. In using large collections you will want to index the field and query it using the below method.
If you want to use an index query using the following:
db.post.find('author' : { "$ref" : 'user', "$id" : 'foo' , "$db" :'database_name' })
If foo is an object id
db.post.find('author' : { "$ref" : 'user', "$id" : ObjectId('foo') , "$db" :'database_name' })
You can create an index on author by
db.post.ensureIndex( {'author' : 1 } );
For anyone looking for a Java solution to this then if you are using mongojack its really easy:
collection.find(DBQuery.is("user", new DBRef(user.getId(), User.class)));
Where collection is a JacksonDBCollection.
In mongoengine you should just use the instance of the referenced object. It should have the ID set.
Suppose the author is the Author document instance. So using this:
Post.objects(author__eq=author)
you can go through all posts of this author.
Post.author should be defined as ReferenceField
Using Mongo 2.4.1 version
This is how you do it on command line for OLA collection where #DBRef dbrefName
db.OLA.find({"dbrefName.someFieldValue" : "Personal"});
Exact query
db.OLA.find({"dbrefName.$id" : ObjectId("1234")});

How to remove _id from MongoDB results?

I am inserting json file into Mongodb(with Scala/Play framework) and the same getting/downloading it into my view page for some other requirement, but this time it is coming with one "_id" parameter in the json file.
But I need only my actual json file only that is not having any any "_id" parameter. I have read the Mongodb tutorial, that by default storing it with one _id for any collection document.
Please let me know that how can I get or is there any chance to get my actual json file without any _id in MongoDB.
this is the json result which is storing in database(I don't need that "_id" parameter)
{
"testjson": [{
"key01": "value1",
"key02": "value02",
"key03": "value03"
}],
"_id": 1
}
If you have a look at ReactiveMongo dev guide and to its API, you can see it support projection in a similar way as the MongoDB shell.
Then you can understand that you can do
collection.find(selector = BSONDocument(), projection = BSONDocument("_id" -> 0))
Or, as you are using JSON serialization:
collection.find(selector = Json.obj(), projection = Json.obj("_id" -> 0))
You can use this query in the shell:
db.testtable.find({},{"_id" : false})
Here we are telling mongoDB not to return _id from the collection.
You can also use 0 instead of false, like this:
db.testtable.find({},{"_id" : 0})
for scala you need to convert it in as per the driver syntax.

Unable to get the value of a MongoDB key

2 days old to Mongo, so bear with me.
I have a collection from which, I only want to retrieve specific values contingent to another key existing in the MongoDB environment.
Here is what I am doing:
db.results.find({'someKeyThatShouldExist':{$exists:true}}, {"parentKey.childKey.theKeyWoseValueIwant":1}
This yields data in the following format for me:
{ "_id" : ObjectId("532a2c2b6803fa486b8b456a"), "parentKey" : { "childKey" : { "theKeyWhoseValueIWant" : 102982577 }}}.....
Now, all I really want is the value 102982577, not everything else.
How can I do this ?
You can suppress the _id by adding _id:0 to the projection criteria.
db.results.find(
{"someKeyThatShouldExist":{$exists:true}},
{_id:0, "parentKey.childKey.theKeyWoseValueIwant":1}
)
To get just the value, you could do something like:
db.results.find(
{"someKeyThatShouldExist":{$exists:true}},
{_id:0, "parentKey.childKey.theKeyWoseValueIwant":1}
)[0].parentKey.childKey.theKeyWoseValueIwant

Cast field in pymongo query

I feel like this should be trivial.
I have a record like :
{'f1' : 1, 'f2' , 'aaaa'}
When I query for that I want to be returned :
{'f1' : '1', 'f2' , 'aaaa'}
Where I have simply cast the int as a string. I don't believe I should have to use the aggregation framework to accomplish this.
I imagine there is someway to pass a JS function but I don't know that magic.
Edit:
Answering my own question to some degree.To do this with aggregation framework. It would be as simple as.
db.datasets.aggregate({$match : {f1:{$ne:null}}},{ $project : {f1: {$toUpper:"$f1"}, f2 : 1 }})
Neither MongoDB nor PyMongo provides a feature like this. You could try adding a "SON manipulator" to transform the outgoing document (that is, the document being retrieved out of the database). But by far the easiest method is:
for doc in db.datasets.find():
doc['f1'] = str(doc['f1'])
do_something_with(doc)

use $lt or $gt operator in mongodb queries

My collection structure*"countcollection"* is looks as below
{
"limitcount": 10000,
"currentcount": 100
}
I want to right the mongoquery that able to compare the currentcount<($lt)limitcount
or currentcount>($gt)limitcount.
First, i wrote the mongo query as below
db.countcollection.find({"currentcount":{$lt:{"limitcount"}}});
db.countcollection.find({"currentcount":{$gt:{"limitcount"}}});
but it's failed to execute .
please give your input for this mongoquery.
thanks in advance .
javaamtho.
As Bugai13 said, you can't do a comparison on 2 fields in a query.
The problem with $where is performance - as that is a javascript function that will be executed for every document so it will have to scan through every one.
So, you could store another field (that you could then index) alongside those existing fields
e.g.
{
"limitcount": 10000,
"currentcount": 100,
"remainingcount" : 9900
}
so you could then query on the new field instead:
db.countcollection.find({"remainingcount" : {$gt : 0}})
db.countcollection.find({"remainingcount" : {$lt : 0}})
You can't do what you want using simple query(like you have tried above). There is such bug in mongodb jira and you can vote up for this.
I suppose you shoud use javascript expression like this:
db.countcollection.find( { $where: "this.currentcount < this.limitcount" } );
Hope this help.
$gt:{"limitcount"}}
does not make any sense since you are comparing against the string limitcount. If you want to compare against a pre-defined variable, use the variable but something with quotes around it. Why did you choose this strange syntax?