MongoDB/PyMongo find_one_and_update and/or find() method doesn't find specified entry, just appends to the end of the collection - database

I'm attempting to search in an array in my collection, to find by a key named "id". Both the find() method and find_one_and_update() don't return the entry I'm trying to find. The collection is structured like so:
"_id" : {stuff},
"events":[{
"id":"12345",
"date":"01/01"
}, {
"id":"12346",
"date":"02/02"
}]
Trying find() as:
result = db.get_collection("events").find({"events.id" : "12345"})
for item in result:
print(item)
Prints out the entire collection.
Trying to update a specific entry by its id like so will append it to the end.
db.get_collection("events").find_one_and_update({"events.id" : "12345"},{"$set" : {"date" : "somedate"}})
Looks like this afterwards:
"id":"12346",
"date":"02/02"
}], "date" : "somedate"
So, what am I doing wrong with updating and finding here? Every other person seems to have no trouble with this part.

Figured this out on my own, needed to specify which object + field to update in the collection:
db.get_collection("events").find_one_and_update({"events.id" : "12345"},{"$set" : {"events.$.date" : "somedate"}})

Related

Firebase: query by array field itself(not by an item of the array)

in my 'rooms' collections, each document has the fields like the following,
{
"createdAt" : 2020.6.4 12:00,
"titleArray" : ["icecream", "summer"]
}
And I want to query to check if a collection contains a document with ["icecream", "summer"] as "titleArray" field, I couldn't find a way to query by an array field itself. In other words, is there a way to passing in an array directly?

TextCriteria with diacriticSensitive. Spring Data MongoDB 1.10.9

I'm trying to create a search in my MongoDB database to search the "name" field without taking into account the accents
I need to create an index in the field:
// create index
#Indexed
#Field("nombre")
private String nombre;
Check in the BBDD that it is created correctly:
db.empleado_bk.getIndexes();
{
"v" : 2,
"key" : {
"nombre" : 1
},
"name" : "nombre",
"ns" : "elser2.empleado_bk"
}
I modify my repository to search in text without taking accents into account
if (StringUtils.isNoneBlank(dtoFilter.getNombre())) {
query.addCriteria(TextCriteria.forDefaultLanguage().diacriticSensitive(true).matching("nombre"));
}
But when looking for that field, I get the following error:
org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 27 and error message 'text index required for $text query'
Can someone tell me if I'm doing something wrong if I need to do something else
You applied a standard index with #Indexed. To apply a text search index, you need to use #TextIndexed.

MongoDB Convert String to Array

I'm very new to MongoDB and experience some difficulties in importing data into the database. Now I have a collection of documents which looks like
db.Question.findOne()
{
"_id" : ObjectId("124"),
"Answers" : "[\"502\",\"784\",\"1060\"]",
}
The Answers are now stored as a single string. However I want to convert it to a list like below so I could unwind it when doing query.
{
"_id" : ObjectId("124"),
"Answers" : ["502","784","1060"],
}
Any idea how to do it ? Thanks.
You can use JSON.parse() to change string type to list and then save the collection with update element. Below is a example:
db.Question.find({}).snapshot().forEach(function (el){el.Answers=JSON.parse(el.Answers);db.Question.save(el)});
You simply need to apply JSON.parse to each of these strings:
> JSON.parse("[\"502\",\"784\",\"1060\"]")
[ '502', '784', '1060' ]
First remove "[" and "]" in the data, then use below code, which create a new attribute,answers, which is a array/list that holds individual numbers:
db.Question.find({}).snapshot().forEach(function (el) {
el.answers=el.Answers.substring(1,el.Answers.length-1);
el.answers = el.Answers.split(',');
db.Question.save(el);
});

Why I dont see array's element when I do db.collection.find()?

I've got a mongo model like this:
attributes:[String]
But when I do : db.ads.find({})
I've got this:
{ "_id" : ObjectId("5571fe998f6319ed03235522"), "attributes" : [ ], "__v" : 0 }
I don't see the elements in the array "attributes" even if actually the array contains this: ["Meublé","Wi-Fi","Salle de sport"]
I would like to be able to do a command like db.ads.find({}) and see the element inside the array
Thanks
Are you doing this in the terminal or your code?
If you are using the terminal:
Use----> db.ads.find()
OR---> db.ads.find().pretty()
to make it look good
Please try to execute in your console the following query:
db.ads.find({"attributes": { $not: { $size: 0 } } })
in order to find all documents that have non-empty "attributes" array.
In your case it looks like you might have many documents with this array empty and db.ads.find() returns a cursor which shows in your console only 20 elements in each iteration (by default), so in first iteration you may be seeing only those that have no values in "attributes".
Hope this will help a little.

Mongo query item from subarray, having trouble

I'm relatively new to mongodb, and I came into this company's set up that had the database already set up and running. It looks to me like the structure of this "array" isn't actually a proper array. They are saving info that I need in "offer_info_array" - which then has a nested array with an "offer id" which changes a lot between records, and then nested inside that is the info that I need to select. Here is an example of a record.
{
"_id" : ObjectId("52041af3bbf8057203000004"),
"offer_info_array" : {
"128" : {
"affid" : "68",
"s1" : "YJF"
}
},
"city" : "Cleveland",
"state" : "OH",
"zip" : "44111"
}
So from a whole db of records like this one, I need to find all records that have the "affid" of "68" - I realize this database is not structured correctly, but there's not much I can do about that for records that already exist. The "128" is the offer id that varies from record to record.
If anyone has any insight and can help me out with this, I would greatly appreciate it. Thank you!
You can use $where operator which accepts JavaScript function:
db.items.find({$where: function() {
for(var key in obj.offer_info_array)
if(obj.offer_info_array[key].affid == 68)
return true;
return false; }})
This function looks for properties of offer_info_array object and gets value of property by key. Then we verify if property value has affid property equal to 68. If yes, we return true which means objects matches our query. If there is no properties with affid equal to 68, we return false.
Keep in mind, that $where operator do not use indexes.

Resources