why is mongodb not indexing my collection - mongodb

I have created a collection and added just a name field and tried to apply the following index.
db.names.createIndex({"name":1})
Even after applying the index I see the below result.
db.names.find()
{ "_id" : ObjectId("57d14139eceab001a19f7e82"), "name" : "kkkk" } {
"_id" : ObjectId("57d1413feceab001a19f7e83"), "name" : "aaaa" } {
"_id" : ObjectId("57d14144eceab001a19f7e84"), "name" : "zzzz" } {
"_id" : ObjectId("57d14148eceab001a19f7e85"), "name" : "dddd" } {
"_id" : ObjectId("57d1414ceceab001a19f7e86"), "name" : "rrrrr" }
What am I missing here.

Khans...
the way you built your index is correct however building an ascending index on names wont return the results in ascending order.
if you need results to be ordered by name you have to use
{db.names.find().sort({names:1})}
what happens when you build an index is that when you search for data the Mongo process perform the search behind the scenes in an ordered fashion for faster outcomes.
Please note: if you just want to see output in sorted order. you dont even need an index.

You won't be able to see if an index has been successfully created (unless there is a considerable speed performance) by running a find() command.
Instead, use db.names.getIndexes() to see if the index has been created (it may take some time if you're running the index in the background for it to appear in the index list)

Related

Issue with cosmos DB collection order

I'm trying to order my collection using the following query:
db.getCollection('trip').find().sort({'itinerary.0.timestamp': 1})
The result is not being correctly sorted, however I exported the full collection to a local mongoDB database and the same query works like a charm. In order to perform that sort in cosmos DB I had to create the index 'itinerary.0.timestamp'.
data example:
{
"_id" : ObjectId("6087104ca68f171ce7715448"),
"tripId" : NumberLong(38533184),
"itinerary" : [
{
"transId" : NumberLong(39800097),
"timestamp" : NumberLong(1619372446291)
},
{
"transId" : NumberLong(39800576),
"timestamp" : NumberLong(1619372446321)
},
],
"results" : [],
"tripTimeSent" : ISODate("2021-04-29T14:44:53.253Z")
}
What am I missing?
Thanks!!
The solution was to create a new field, itiTimestamp, outside the array containing the value 'itinerary.0.timestamp'. Then just order by itiTimestamp
It's true that you need to create an index for the sort field. Here's the doc related:
To apply a sort to a query, you must create an index on the fields
used in the sort operation.
==========================================
I've tested in my side, after creating wildcard index on itinerary, sort query could be executed but has no luck. I also refer to this answer(new BasicDBObject("labels.0.value", 1)) and this one(db.testCollection.find().sort({"someArray.0": 1})), they all don't work for the date format Op provided.
But when I added a properity "score":[20,55,80] in each item in the collection, I found it can be sorted by the first item when sort by score directly.
I assume that this feature hasn't supported.

Updating documents with nested arrays based on conditions

I'm new to MongoDB and have to work on a legacy project that I didn't create... and I'm struggling!
I need to reset some documents in one of my collections, based on a particular field value. I have had some success with this so far, but some of the data I need to update is within nested arrays in that document, and I can't work that part out.
Below is an example of one document in the collection:
{
"_id" : ObjectId("1234567890"),
"currentStatus" : "approved",
"itemsInstalled" : [
{
"installDate" : ISODate("2017-04-18T00:00:00.000Z"),
"_id" : ObjectId("1234567890"),
"status" : "approved"
},
{
"installDate" : ISODate("2017-04-18T00:00:00.000Z"),
"_id" : ObjectId("0987654321"),
"status" : "approved"
}
],
"__v" : 5005,
"approvalDate" : ISODate("2017-12-04T10:40:01.580Z"),
"approvedBy" : "automatic"
}
I need to update every document in my collection where the approvedBy field is set to automatic, and leave the others untouched.
For the documents I am updating, I need to remove the approvalDate and approvedBy fields completely, change the currentStatus field to action and change every item in the itemsInstalled array to pending. Everything else can stay as it is.
This is something I would persist with solving myself if I had more time.
Unfortunately, to my knowledge, you can't update multiple array elements. Your best bet is probably to use forEach. You can accomplish what you want with something like this:
db.your_collection.find({
approvedBy: "automatic"
}).forEach(function(doc) {
for(var i = 0; i < doc.itemsInstalled.length; i++) {
doc.itemsInstalled[i].status = "pending";
}
doc.currentStatus = "action";
delete doc.approvedBy;
delete doc.approvalDate;
db.your_collection.update({_id: doc._id}, doc);
});
Using forEach, you can update all of the array elements at once. The downside is that you will be performing multiple update queries, so you should be careful about doing this on particularly large collections or as part of your application logic. Ideally this should be a one-time use scenario.

MongoDB Compound text search

I have a collection like this in my mongo database, let's say it's called taxonomic.
{
"_id" : ObjectId("5810e15a762a39b41912a131"),
"validName" : "Eros",
"idUser" : ObjectId("1")
}
{
"_id" : ObjectId("5810e15a762a39b41912a132"),
"validName" : "Eros",
"idUser" : ObjectId("2")
}
I've already created a compound index to be able to search for the two values I want, such as this.
db.taxonomic.createIndex({"idUser":1,"validName":1})
Now, I want to be able to search and get a return from it only when both of the parameters are found on the same document of the collections, here's my try:
db.taxonomic.find({$text:{$search:"Eros 2"}},{idUser:1,validName:1})
The problem with this method is that it will return any match of "Eros" OR "2", what I want is a return of the values when "Eros" AND "2" are matched in a document of the collection.
Thank you for any help!
I dont think you require a text Index for it if you only want specific string
db.taxonomic.find({"$or" : [{"validName" : "Eros"},{"validName" : "2"}]},{idUser:1,validName:1})

Search full document in mongodb for a match

Is there a way to match a value with every array and sub document inside the document in mongodb collection and return the document
{
"_id" : "2000001956",
"trimline1" : "abc",
"trimline2" : "xyz",
"subtitle" : "www",
"image" : {
"large" : 0,
"small" : 0,
"tiled" : 0,
"cropped" : false
},
"Kytrr" : {
"count" : 0,
"assigned" : 0
}
}
for eg if in the above document I am searching for xyz or "ab" or "xy" or "z" or "0" this document should be returned.
I actually have to achieve this at the back end using C# driver but a mongo query would also help greatly.
Please advice.
Thanks
You could probably do this using '$where'
db.mycollection({$where:"JSON.stringify(this).indexOf('xyz')!=-1"})
I'm converting the whole record to a big string and then searching to see if your element is in the resulting string. Probably won't work if your xyz is in the fieldnames!
You can make it iterate through the fields to make a big string and then search it though.
This isn't the most elegant way and will involve a full tablescan. It will be faster if you look through the individual fields!
While Malcolm's answer above would work, when your collection gets large or you have high traffic, you'll see this fall over pretty quickly. This is because of 2 things. First, dropping down to javascript is a big deal and second, this will always be a full table scan because $where can't use an index.
MongoDB 2.6 introduced text indexing which is on by default (it was in beta in 2.4). With it, you can have a full text index on all the fields in the document. The documentation gives the following example where a text index is created for every field and names the index "TextIndex".
db.collection.ensureIndex(
{ "$**": "text" },
{ name: "TextIndex" }
)

Mongodb - combine data from two collections

I know this has been covered quite a lot on here, however, i'm very new to MongoDB and am struggling with applying answers i've found to my situation.
In short, I have two collections 'total_by_country_and_isrc' which is the output from a MapReduce function and 'asset_report' which contains an asset_id not present in the 'total_by_country_and_isrc' collection or the original raw data collection this was MapReduced from.
An example of the data in 'total_by_country_and_isrc' is:
{ "_id" : { "custom_id" : 4748532, "isrc" : "GBCEJ0100080",
"country" : "AE" }, "value" : 0 }
And an example of the data in the 'asset_report' is:
{ "_id" : ObjectId("51824ef016f3edbb14ef5eae"), "Asset ID" :
"A836656134476364", "Asset Type" : "Web", "Metadata Origination" :
"Unknown", "Custom ID" : "4748532", "ISRC" : "", }
I'd like to end up with the following ('total_by_country_and_isrc_with_asset_id'):
{ "_id" : { "Asset ID" : "A836656134476364", "custom_id" : 4748532,
"isrc" : "GBCEJ0100080", "country" : "AE" }, "value" : 0 }
I know how I would approach with in a relational database but I really want to try and get this working in Mongo as i'm dealing with some pretty large collections and feel Mongo is the right tool for the job.
Can anyone offer some guidance here?
I think you want to use the "reduce" output action: Output to a Collection with an Action. You'll need to regenerate total_by_country_and_isrc, because it doesn't look like asset_report has the fields it needs to generate the keys you already have in total_by_country_and_isrc – so "joining" the data is impossible.
First, write a map method that is capable of generating the same keys from the original collection (used to generate total_by_country_and_isrc) and also from the asset_report collection. Think of these keys as the "join" fields.
Next, map and reduce your original collection to create total_by_country_and_isrc with the correct keys.
Finally, map asset_report with the same method you used to generate total_by_country_and_isrc, but use a reduce function that can be used to reduce the intersection (by key) of this mapped data from asset_report and the data in total_by_country_and_isrc.