How to search document using ObjectId in MongoDB (Anypoint Studio) - mongodb

I'm using AnypointStudio to create an API and I'm trying to search for a document using the ObjectId on MongoDB but I can't make it work. I have tried searching with the use of other fields in the collection and it works just fine. Here is the value of the Find query I am currently using.
output application/json
---
{
"_id" : "5c088f4264c73358f4f7e3c0"
}
Here's an example result I have upon searching with the use of the uid field.
{
"_id": {
"$oid": "5c088f4264c73357f4f7e3c0"
},
"uid": "test",
"name": "test",
"validUser": true,
"oauth_client_id": "55628a5730ad44719e63b34c36604401",
"customer": "test customer"
}
Can anyone please help me to search document using the ObjectId? Thanks

I finally got the answer with some experimentations. I noticed the structure of the _id field and tried using this in the query "_id" : {"$oid" : "5c088f4264c73358f4f7e3c0"} but won't work since $ symbol is a reference symbol(?). So I tried using \ before the $ and it works.
output application/json
---
{
"_id" : {"\$oid" : "5c088f4264c73358f4f7e3c0"}
}

The example you show should work, you may need to wrap it like this
{
_id : ObjectId("5c088f4264c73358f4f7e3c0")
}
Hope this helps

Related

find() return the latest value only on MongoDB

I have this collection in MongoDB that contains the following entries. I'm using Robo3T to run the query.
{
"_id" : ObjectId("xxx1"),
"Evaluation Date" : "2021-09-09",
"Results" : [
{
"Name" : "ABCD",
"Version" : "3.2.x"
}
]
"_id" : ObjectId("xxx2"),
"Evaluation Date" : "2022-09-09",
"Results" : [
{
"Name" : "ABxD",
"Version" : "5.2.x"
}
]
}
This document contains multiple entries of similar format. Now, I need to extract the latest value for "Version".
Expected output:
5.2.x
Measures I've taken so far:
(1) I've only tried findOne() and while I was able to extract the value of "Version": db.getCollection('TestCollectionName').findOne().Results[0].Version
...only the oldest entry was returned.
3.2.x
(2) Using the find().sort().limit() like below, returns the entire document for the latest entry and not just the data value that I wanted; db.getCollection('TestCollectionName').find({}).sort({"Results.Version":-1}).limit(1)
Results below:
"_id" : ObjectId("xxx2"),
"Evaluation Date" : "2022-09-09",
"Results" : [
{
"Name" : "ABxD",
"Version" : "5.2.x"
}
]
(3) I've tried to use sort() and limit() alongside findOne() but I've read that findOne is maybe deprecated and also not compatible with sort. And thus, resulting to an error.
(4) Finally, if I try to use sort and limit on find like this: db.getCollection('LD_exit_Evaluation_Result_MFC525').find({"Results.New"}).sort({_id:-1}).limit(1) I would get an unexpected token error.
What would be a good measure for this?
Did I simply mistake to/remove a bracket or need to reorder the syntax?
Thanks in advance.
I'm not sure if I understood well, but maybe this could be what are you looking for:
db.collection.aggregate([
{
"$project": {
lastResult: {
"$last": "$Results"
},
},
},
{
"$project": {
version: "$lastResult.Version",
_id: 0
}
}
])
It uses aggregate with some operators: the first $project calculate a new field called lastResult with the last element of each array using $last operator. The second $project is just to clean the output. If you need the _id reference, just remove _id: 0 or change its value to 1.
You can check how it works here: https://mongoplayground.net/p/jwqulFtCh6b
Hope I helped

mongochef azure document db query issue

I am currently using MongoChef (4.3.0) to access an Azure Document DB (using DocumentDB protocol support for MongoDB).
The data in question is from an Application Insights continuous export has the following type of data within (there is other data there but this is the key part i am interested in...)
{
... other fields ...
"request" : [
{
"name" : "GET /images/loading_man.gif",
"count" : NumberInt(1),
"responseCode" : NumberInt(200),
"success" : NumberInt(1),
"url" : "http://<removed>.cloudapp.azure.com/<something>/images/loading_man.gif"
... other fields ...
}
]
... other fields ...
}
Using MongoChef I can perform some basic query like the following without issue;
{ "request": { $exists: true } }
but anything more complicated seems to return nothing or not run at all
{ "request.0.url": { $exists: true } }
{ "request.0.url": /.*man.*/i }
If I Export this data and Import it to my local MongoDb I am indeed able to perform such searches on the data in question without issue.
Any ideas how I could perform this type of search on the data in question without needing to export it?.
(this is a programming issue, because I want to do the above in a python program!)
Well it looks like all I needed to do was use $elemMatch!
{ "request": { $elemMatch: {url:/.*man.*/i } }}
this is as I understand the recommended way but also 'faster'?

Getting MongoDB error - SyntaxError: Unexpected token?

I am a Mongo database. There is a collection called _migrations. I am trying to insert couple of documents into the collection. But I am getting the following error SyntaxError: Unexpected token ?. My code is below.
db._migrations.insert([
{
"_id" : "1_create-organization-collection"
},
{
"_id" : "2_create-dataFilter-collection"
},
{
"_id" : "3_create-application-collection"
},
{
"_id" : "4_migrate-datafilters-to-mongo"
},
{
"_id" : "5_Add-Salesforce-DataFilters"
},
{
"_id" : "6_biq-repository-data-fiter"
}]);
What am I doing wrong?
Can you please trying removing underscore("") in your collection name? I tried with underscore but it did not work for me, but when I tried without underscore("") same data got inserted. So, please try without underscore in your collection name.
_id field value can be inserted after type case with ObjectId. it will work like below -
db._migrations.insert([
{ "_id" : ObjectId("1_create-organization-collection") },
{ "_id" : ObjectId("2_create-dataFilter-collection") }
]);
Please refer below links for more details about the issue:
Is there a convention to name collection in MongoDB?
Mongo client can't access collections prefixed with an underscore
Mongo shell does not support collection name starting with underscore("_")

having difficulty inserting an array of subrecords using $push, getting internal server error

I have the following record that I am trying to create in my database:
{
"userid":
"songs":[
{
"title":
"artist":
}
{
"title":
"artist":
}
]
}
There can be multiple songs under one user. I am unsure of the proper syntax to insert a record with multiple subrecords.I tried using:
Links.insert({userid: "user1", $push: {songs: {"song1","artist1"}}});
I tried using another alternative which is to create the record with only userid field first and then make updates to push songs into the record. However, I get the following error when I do the following:
Links.update({_id: Links.findOne({userid: "user1"})._id, $push: {songs:{"song1","artist1"}}});
Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]
I am confused, since I am using the _id field to update the records. Any suggestions on how to get around this?
Your mongo queries are wrong. These should work (untested):
Insert
Links.insert({
userid : "user1",
songs : [
{ title : "song1", artist : "artist" },
...
]
});
You don't need to push the array in the insert command.
Update
Links.update({
_id : Links.findOne({ userid : "user1" })._id
},
{
"$push" : { title : "song1", artist : "artist" }
});
Note the Update query has two objects passed to it, one is the selector, the second is the modifier to apply.
See http://docs.meteor.com/#selectors

query the value of a sub document in mongodb

I'm using the Java driver withe document that looks like this (a real test example):
{
"_id" : ObjectId("5207fe359b88bfa6f90a82b0"),
"meta_id" : "d6eb1b13-50c7-473f-8348-b5a638a542a0",
"name" : "Fake Name Inc.",
"created" : ISODate("2013-08-11T21:12:21.533Z"),
"members" : {
"5207fe359b88bfa6f90a82af" : [
"Admin",
"User"
]
}
}
I want to select the string array at the path "members.5207fe359b88bfa6f90a82af" (which is a list of roles).
I'm at a loss as to how to do that. It looks like a projection would work here, but I'm new enough to Mongo that the way the projection is written is not obvious.
I can of course load the whole object or maybe even just the "members" field, but I think I should be able to select just exactly the data I'm after.
So, does anyone have an idea of how such a query would be written?
Note: This question suggests that maybe I need to change the structure of the document to make things easier: MongoDB - Query by sub-tree
You can use dot notation in the projection parameter of find to do this. In the shell:
db.test.find(
{_id : ObjectId("5207fe359b88bfa6f90a82b0")},
{'members.5207fe359b88bfa6f90a82af': 1, _id: 0})
Returns:
{
"members": {
"5207fe359b88bfa6f90a82af": [
"Admin",
"User"
]
}
}