MongoDB - get documents between dates using ObjectID - mongodb

As the title said, I want to get documents between 2 dates using the ObjectID. In mongoose I use _id: { $gte: ObjectID.createFromTime(new Date("2019-01-01")) } but I can't figure it out how to construct this query on mongo shell. There is a post on StackOverflow which lists different queries on mongo shell and mongoose but I can't seem to find that post. Does anyone know how to do the same query on mongo shell? Thanks.
UPDATED
Since I have already found the solution, does anyone know why the method names are different in mongo shell and mongoose? This really causes confusion sometimes.

Figured it out, it's _id: { $gte: new ObjectId.fromDate(new Date("2019-01-01")) } on mongo shell

Related

mongodb compass query with objectId in date range

I'm trying to perform a date range query on the _id field using compass.
I've tried what I found here with the following filter:
{_id: { $gte: ObjectId.fromDate(new Date('2019-01-01')) } }
What am I missing? I'd like to get a list of all documents from some date forward (in this example from 1 Jan 2019 to present). Unfortunately there isn't a timestamp in the document fields so I need to extract it from the object id.
You need to pass a date object to the ObjectId.fromDate, not a string. Try this:
ObjectId.fromDate(new Date('2019-01-01'))
This function works only in the shell and doesn't exist in the drivers.
EDIT after comments:
Here is a solution that works in Compass as well:
{
$expr: {
$gte: [
{"$toDate":"$_id"},
ISODate("2021-01-01T00:00:00.000Z")
]
}
}
Keep in mind, however, that it requires a version of mongo of 4.0+. You can checkout the docs here.
Also, checkout this related topic: Can I query MongoDB ObjectId by date?
It is not about Compass, but it provides solutions for generating the ObjectIds from a date without being dependent on ObjectId.fromDate().
I found a solution, maybe not the best but it does the job. Hopefully this can help someone with the same problem if there isn't a cleaner solution.
I converted the date I needed to an ObjectId outside of compass online here.
Then I wrote the query with that ObjectId:
{_id: { $gte: ObjectId(' object id here ') } }
As suggested in the comments, see this related topic. It's not specific to Compass but it provides a solution for generating ObjectIds from a date without being dependent on ObjectId.fromDate().

MongoDB Compass does not allow ObjectId() while populating DB with "Insert Document" feature?

I am using MongoDB Compass version 1.25.0.
I was trying to insert a document shared by one of my colleague using the "Insert Document" feature of the MongoDB Compass.
But, it's showing that the document is not in correct format.
I think it is validating JSON format and ObjectId() is not a valid JSON value.
I am aware that Compass would create ObjectId() automatically but I want to pass it explicitly.
I resorted to the Shell and I was able to insert the document.
My question is does MongoDB Compass allow entering ObjectId() from the UI?
If yes, what am I doing wrong?
I was able to insert a document with ObjectId using below syntax:
{
"_id": {
"$oid": "60261ccf416a1ed478d7357a"
}
}
I found that the documentation of a bit off in clarifying how the $oid is supposed to be used.
At least for someone beginner like me.

Issues updating subdocuments in mongodb

Excuse if this is a silly question, but I'm quite new to mongo.
I have documents with subdocument listed under films. I'm updating a single subdocument without issue on my localhost using;
db.update(
{ _id: req.params.id, 'films.filmId': req.params.filmId },
{ $set: {
'films.$.watched': watched,
'films.$.watchedAt': watchedAt
}})
However, when testing it on Heroku with mLab it only ever updates the first subdocument listed in films, regardless of the filmId passed to it.
This update is only updating the first array element because its using the $ operator.
The $ operator is a placeholder for the first element in the array that matches the query document. Documentation on this operator in the context of an update can be found here.

Meteor React - Why is findOne on a single document not found in miniMongo when it does exist?

This is such a weird problem. I think it has to do with how I am querying the document. It seems like the Meteor API has changed to query documents but the docs on the website are the same.
Here is a document in the database:
meteor:PRIMARY> db.studies.findOne()
{ "_id" : ObjectId("56c12e6537014a66b16771e7"), "name" : "Study 1" }
I have subscribed to get all documents and here is what I am trying in the console to get the documents.
var study = Studies.findOne() // This works.
It returns:
_id: MongoID.ObjectID
_str: "56c12e6537014a66b16771e7"
name: 'Study 1'
I just started a new Meteor project with React. I see that my collection is returning _id: MongoId.ObjectId
This is different, I have been using Meteor for awhile with Blaze and I can't remember it returning MongoID.ObjectID instead of just the string
But now if I try and find just that one document, it does not work.
var study = Studies.findOne("56c12e6537014a66b16771e7");
or
var study = Studies.findOne({_id: "56c12e6537014a66b16771e7"});
I am positive I am queuing for the right _id field. I have double checked the ID. Why does trying to find this one document not work?
Please let me know how I can query for a document. Has something changed with Meteor? The documentation still says you can search by id string.
You need to explicitly cast object id string to an ObjectID
var study = Studies.findOne({_id: new Meteor.Collection.ObjectID("56c12e6537014a66b16771e7")});
#Jaco has the correct answer, but I wanted to answer here to clarify what the higher level issue was.
The reason why my find query was not following syntax in Meteor docs is because I inserted the document into MongoDB directly, instead of through the Meteor API.
If you insert the document directly into MongoDB, you have to query the document using the syntax #Jaco mentioned in his answer.
Similar question: Meteor - Find a document from collection via Mongo ObjectId
So instead of changing my query code, I just deleted the document I inserted directly into MongoDB, and inserted a documented using the console in the browser.
Now I can query the document like normal.
So the root of the issue is that if you insert the document directly into MongoDB, you don't get the same type of document as you would if you insert the document using the Meteor API.

Trouble updating last document from a query

Hello I'm new to Mongodb, I am currently trying to update the last document in a query result but having trouble doing so.
I know how to get the last document using
db.collection.find().sort({$natural:-1}).limit(1)
but how do I update this? I tried doing:
db.collection.update(db.collection.find().sort({$natural:-1}).limit(1))
But that didn't work. And I don't think:
db.collection.update(query,update,option).sort({$natural:-1}).limit(1))
would do what i want. I checked the official documentation but couldn't find anything on querying only for the last document.
You can use findAndModify to perform an update that requires sorting to identify the document to update:
db.test.findAndModify({
query: {},
sort: {$natural: -1},
update: {$set: {foo: 'bar'}}
})
You can also do it this way:
var id = db.collection.find().sort({$natural:-1}).limit(1)[0]['_id'];
db.collection.update({_id: id},{...})