Strange behavior in Studio3T/Mongo - mongodb

As the Title suggests, I found a rather strange behavior which I am not sure to attribute to Studio3T or to MongoDB.
I have a collection containing simple documents, as follows:
Example of a document in the collection
Whenever I perform a query using the query builder, everything works as expected. However, when I do it using IntelliShell or Aggregate AND if such query is based on the field StudyID, no document is returned, regardless the query.
For example, the two following queries return, respectively, an empty list and no documents.
db.Cortisol.distinct("StudyID")
db.Cortisol.find({},{"StudyID" : 1})
While the following very similar query returns the documents, as expected.
db.Cortisol.find({},{"ExamID" : 1})
As you can see the queries are correct, I did not misspell anything so does anyone have a possible explanation for such a strange behavior?

I wonder if your field "StudyID" contains some weird (invisible) unicode chars. This would explain why dragging the field into query builder works (because the query builder uses the exact same string) and typing S-t-u-d-y-I-D doesn't.
When you run an empty query and you see documents with StudyID returned, can you then copy the field name of your StudyID field to the clipboard, and then when you type your query in IntelliShell paste the StudyID name?

Related

MongoDB Query - Filter only works with "_id"

I'm using mongodb v4.0.3, and this happens both with the shell and in compass.
This only happens with a certain collection. It previously had overriden ids (instead of the default mongodb id, there was a string. I dropped the collection and I recreated it without that).
I have the following structure ("mystructure"), for example:
{
"_id":ObjectId("5bd44eb528d61e3374b5e6ea"),
"custom_field":"data",
}
When I query it without a filter it returns all the docs:
db.mystructure.find({});
When I search for its objectid, it returns properly
db.mystructure.find( {"_id": ObjectId("5bd44eb528d61e3374b5e6ea")} );
But when I try to filter with any field, it doesn't return anything
db.mystructure.find( {"custom_field": "data"} );
At first I thought it would be solved recreating the collection with the automatically generated ids from mongodb but the problem persists. There are no "hidden" spaces in the string or anything like that. The same query in compass isn't working either. Other collections do work. It's on the same db, with the same user.
Why can this be?
Thank you very much.
you should write below code where 62c01e5a763d106152a2e53f is your _id
{_id:ObjectId('62c01e5a763d106152a2e53f')}

Can't find documents by criteria containing string objectId value

I have a collection list such:
{username: 'somename',
friendId: '57d725d6b8b144044602bf74' <-- This a reference objectId to another doc
}
When I query docs in my collection with criteria {friendId : '57d725d6b8b144044602bf74'} I get no results back .
Any other field query works fine.
I tried to convert the value to ObjectId('57d725d6b8b144044602bf74') even though the value is just a string, still no go.
Why am I failing to search for by that type of string ?
you are trying to achieve 'self-join' in mongoDB and you seems to rely on the _id field generated by mongodb.
i would suggest you to supply custom _ID fields to the document.
eg:
{_id:"alex", name:"alex", friendID:""}
{_id"john", name"john", friendID:"alex"}
and then you can execute your queries with ease on friendID field. Give it a shot and see if this make sense for your requirement.

Mongo DB search based on multiple conditions

I am trying to search based on multiple conditions which works but the problem is that does not behave like this.
Assuming i have a search query like
Orders.find({$or: {"status":{"$in":["open", "closed"]},"paymentStatus":{"$in":["unpaid"]}}}
)
and i add another filter parameter like approvalStatus it does not leave the previously found items but rather it treats the query like an AND that will return an empty collection of items if one of the queries does not match.
How can i write a query that regardless of what is passed into it, it will retain previously found items even if there is no record in one of the conditions.
like a simple OR query in sql
I hope i explained this well enough
Using $or here is the right approach, but its value needs to be an array of query expressions, not an object.
So your query should look something like this instead:
Orders.find({$or: [
{"status": {"$in": ["open", "closed"]}},
{"paymentStatus": {"$in": ["unpaid"]}},
{"approvalStatus": {"$in": ["approved"]}}
]})

MongoDB: min(), max() doesn't support embedded document

I have applied index on embedded document field which is of type date. Due to unpredictable behavior of MongoDB query with $lt & $gt operators I am trying to use min() max() functions of Cursor which force both lower & upper bounds on the index. But when I used it, it gave me error:
planner returned error: unable to find relevant index for max/min query"
Query looks like:
db.user.find().min({'record.date':ISODate("2014-12-01")}).max({'record.date':ISODate("2014-12-01")}).explain()
I have indexed the field 'record.date'. I even tried to force it with hint() but of no use. It showed me this error:
planner returned error: hint provided does not work with min query"
Somewhere on the Internet I saw on one of the forums that we can query with embedded fields in min(), max() functions. Field 'record' is an array of sub-documents. I have another field of type date in main document for which min(), max() worked fine (this field is indexed too). Can anyone guess why is this happening?
sample document:
user:
{name:'ad',dob: ISODate('yyyy-mm-dd'),createdAt: ISODate(),...,record:[
{date:ISODate:(),...
},...]}
Index was created as:
db.user.ensureIndex({'record.date':1})
Thanks.

updating/inserting subdocument mongodb

I clearly don't understand how I update / insert a subdocument in an existing document.
I tried the following:
query = aCollection.find_one({stuffToFind})
aCollection.update(query,
{"$set": {"subDoc" : {"1" : String, "2" : datetime.datetime.now(), "3" : otherString}}})
this only works one time but I want to constantly change the subDoc's Data 1,2 and 3 if this code is executed. find_and_modify also fails, because it seems to overwrite the whole document deleting all other fields but the id and those specified in update.
Since I'm pretty new to MongoDB it would be nice if someone could give me a code example how to figure out my problem.
Edit: without the "$set" statement it remains unchanged as well on a second execution..
Edit2: this seems to work, eventhough I'm unable to edit the affected (JSON)document directly in MonjaDB anymore :D
aCollection.update(query(but this time not as a variable),
{"$set" : {"subDoc.1" : Sting, "subDoc.2" : datetime.datetime.now(), "subDoc.3" : otherString}})
I dont know, why this is working so maybe someone could explain what I did wrong..
Thanks in advance,
Codehai
The query you supply to update in the first example is not correct, instead of:
query = aCollection.find_one({stuffToFind})
you should have:
query = {stuffToFind}
The reason that the update does not throw an error is that the result of find_one is a dictionary. Note also that sometimes the above will even work since in the update you are actually asking MongoDB to match the whole document that corresponds to the initial
query. Subsequent uses of query of course in that case will not bring the expected results since the document will have been changed from the update.
The $set updates only the keys that we specify leaving everything else untouched. That means that if we update an embedded object then the whole embedded object will get replaced with what we specify in $set. If we want to pinpoint keys in the embedded object
we must use dot notation as you do in the second example.