I have a collection in MongoDB with two dates that define whether or not something is current. So I have an "end_date" that can be null, or may have a time value. An item that current has a null end_date or a time in the future. My query looks like this:
program_enrollments.find( {"start_date":{"$lte":1376982000},"end_date":[null,{"$gte ":1376982000}],"client":"52002d02cc94a31a0f000000"}, [] )
This looks proper to me, but do I need a different approach? I don't want to have a boolean flag that says whether or not the dates are current if I can avoid it.
MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).
Use BsonNull. Value with the MongoDB C# driver to query for null or missing fields in MongoDB.
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
You are looking for the $or
operation, which accepts an array of operations. It would be like so:
$or: [{end_date: null}, {end_date: {$gte: 1376982000}}]
Your entire query would look like:
program_enrollments.find({ start_date: {$lte: 1376982000}, $or: [ {end_date: null}, {end_date: {$gte: 1376982000}} ], client:"52002d02cc94a31a0f000000" })
To scale, you will want to find a way to remove either the $gte
and $lte
operators. MongoDB cannot use the combination of the $lte
and $gte
on different attributes in the query.
The $or operator could be quite cumbersome at times, especially if you have other fields with multiple options, then you'd have to put all the $or's nested within an $and.
Another option could be to use the negation operator:
"end_date": {"$not": {"$lt":1376982000}}
This will give you the same results as
$or: [{end_date: null}, {end_date: {$gte: 1376982000}}]
And your query would look like this, which is somewhat cleaner IMO:
program_enrollments.find({ start_date: {$lte: 1376982000}, end_date: {$not: {$lt: 1376982000}}, client:"52002d02cc94a31a0f000000" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With