[MongoDB]How to find an object from array? - arrays

I'm trying to query single object from an array of objects.
The array looks like this.
db.getCollection('user').getIndexes();
[
{
"v" : 1,
"key" : {
"_id" : 1
}
},
{
"v" : 1,
"key" : {
"name" : 1
}
},
{
"v" : 1,
"key" : {
"admin" : 1
}
}
]
Don't know how to find an element with "_id" property name in "key" object.
db.getCollection('user').getIndexes().[some sorting query];
{
"v" : 1,
"key" : {
"_id" : 1
}
}
Does anyone have an idea? Thank you.

The getIndexes helper in the mongo shell accepts a filter as an argument, like:
db.getCollection("user").getIndexes({"key._id":{$exists:true}})
From a driver, you can run the listIndexes command similarly:
database.runCommand({listIndexes:"user", "key._id":{$exists:true}})

Related

mongodb updateMany nested array

I've got the following object and want to update
ArrayOne.ArrayTwo.DocumentTypeID from that ID to a different ID:
{
"_id" : NUUID("97cd06e9-3449-45db-be69-fce30ee1f9b8"),
"ArrayOne" : [
{
"ID" : NUUID("70d99c86-414c-401a-9cc9-91661806c10f"),
"ArrayTwo" : [
{
"EvidenceID" : NUUID("0799492a-b312-4832-a830-ce4ff841d5fd"),
"DocumentTypeID" : NUUID("fa67acee-2d56-4174-954f-f1bdc892add0"),
"FileID" : NUUID("e5f433c6-8c7f-008d-6d2a-12a908f91690"),
"FileName" : "testqwerty.pdf",
"AdjudicationStatus" : 0,
"SubmitDateTime" : ISODate("2022-09-12T14:14:15.060Z")
}
],
"Propertyone" : null,
"Propertytwo" : null,
"Propertythree" : 0
}
]
}
Trying to use:
db.getCollection('Collection').updateMany
(
{"ArrayOne.ArrayTwo.DocumentTypeID" : NUUID("FA67ACEE-2D56-4174-954F-F1BDC892ADD0")},
{$set : {"ArrayOne.ArrayTwo.DocumentTypeID" : NUUID("090F89EF-3AAE-45F2-853F-5B8C7B8AC0CA")}}
)
I do not want to specify the element as 'ArrayOne' can have up to 10 elements and so can "ArrayTwo" the DocumentTypeID however has a unique GUID.
Can someone please let me know how I can do this ?
Thanks

Arabic text in swift

i have array of objects like this
"sub-specialty" : [
{
"id" : 1,
"title" : "Adult Physiotherapy",
"ar_title" : "علاج طبيعي بالغين",
"name" : "علاج طبيعي بالغين"
},
{
"id" : 2,
"title" : "Pediatric Physiotherapy",
"ar_title" : "علاج طبيعي اطفال",
"name" : "علاج طبيعي اطفال"
},
{
"id" : 3,
"title" : "Sport Injuries",
"ar_title" : "اصابات ملاعب",
"name" : "اصابات ملاعب"
},
{
"id" : 4,
"title" : "Rehabilitation",
"ar_title" : "تأهيل",
"name" : "تأهيل"
}
]
when i use map to grab name only like this
let sub = sub-specialty.map({($0.name ?? "")}).joined(separator: ", ") ?? ""
i got rubbish characters or text is flipped please see the attached image
enter image description here
You need to get the text as String and set wherever you want to set. It will work fine. I have worked with multi languages and this work for me.

Rename a sub-document field within an Array of an Document

I am trying to rename the particular child field inside an array of an collection in MONGODB
{
"_id" : Id("248NSAJKH258"),
"isGoogled" : true,
"toCrawled" : true,
"result" : [
{
"resultsId" : 1,
"title" : "Text Data to be writen",
"googleRanking" : 1,
"isrelated" : false
},
{
"resultId" : 2,
"title" : "Text Data",
"googleRanking" : 2,
"isrelated" : true
}]
**I need to rename "isrelated" to "related" ** from the collection document
Using mongo Version 4.0
I Tried :
db.collection_name.update({}, { $rename: { 'result.isrelated': 'result.related'} } )
But it didn't worked in my case
As mentioned in official documentation $rename not working for arrays.
Please check link below:
https://docs.mongodb.com/manual/reference/operator/update/rename/
But you can do something like this
let newResult = [];
db.aa1.find({}).forEach(doc => {
for (let i in doc.result) {
newResult.push({
"resultsId" : doc.result[i]['resultsId'],
"title" : doc.result[i]['title'],
"googleRanking" : doc.result[i]['googleRanking'],
"related" : doc.result[i]['isrelated'],
})
}
db.aa1.updateOne({_id: doc._id}, {$set: {result: newResult}});
newResult = []
})

Changing Type Array in Mongodb

I mistakenly created a variable as an array and would like to remove the first element of the array and change the array type to simple strings.
I have been playing around with changing types in mongo from integer to strings and using the $set to change strings to arrays, however I am unable to find a solution to this variation.
The following is the a piece of the document:
db.test.find({"ids":"XXX"}, {"accountability":1}).pretty()
{
"_id" : ObjectId("524c26006f73207e0d977522"),
"accountability" : [
{
"environment" : null,
"performance" : null,
}
]
}
However when I tried to index it, the following appears:
db.test.find({"ids":"XXX"}, {"accountability.performance":1}).pretty()
{
"_id" : ObjectId("524c26006f73207e0d977522"),
"institution" : {
"accountability" : [
{
"performance" : null
}
]
}
}
db.test.find({"ids":"XXX"}, {"institution.accountability.0":1}).pretty()
{
"_id" : ObjectId("52435f0f6f73205f7d37a2b0"),
"accountability" : {
}
}
And lastly:
db.test.find({"ids":"XXX"}, {"accountability.0.performance":1}).pretty()
{
"_id" : ObjectId("524c26006f73207e0d977522"),
"accountability" : [
{
}
]
}
I would appreciate any advice!
Thank you!

update nth document in a nested array document in mongodb

I need to update a document in an array inside another document in Mongo DB
{
"_id" : ObjectId("51cff693d342704b5047e6d8"),
"author" : "test",
"body" : "sdfkj dsfhk asdfjad ",
"comments" : [
{
"author" : "test",
"body" : "sdfkjdj\r\nasdjgkfdfj",
"email" : "test#tes.com"
},
{
"author" : "hola",
"body" : "sdfl\r\nhola \r\nwork here"
}
],
"date" : ISODate("2013-06-30T09:12:51.629Z"),
"permalink" : "jaiho",
"tags" : [
"jaiho"
],
"title" : "JAiHo"
}
Q1) Update email of 0th element of comments array
db.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})
This doesn't throw any exception but doesn't update anything as well
Q2) Add a field on nth element of comments array number_likes
db.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})
Doesn't work either.
Am I missing something here?
Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email;
> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}})
> db.posts.find()
..., "email" : 1 },...
Q2: Same goes for this include;
> db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}})
> db.posts.find()
..., "num_likes" : 1 },...
If you are trying to do it dynamically in Node JS following should work.
i = 0;
selector = {};
operator = {};
selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1}
operator['$inc'] = selector; // {'$inc' : {'comments.0.num_likes' : 1} }
db.posts.update({'permalink' : 'xyz'}, operator);

Resources