Hyphen in subcollection name - javascript

I have made a mistake naming subcollection in MongoDB, unfortunately I named them using hyphen :/
Here is sample :
{
id: "..."
"A-Section": {
"val":1
}
}
I need to access the "val" field. Unfortunately hyphens seems to block MongoDB.
So I have to option :
Find a trick to access the "A-Section"
Rename all the "A-Section"
In both case I do not know how to do it and after few researches, I only found answer if the collection name contains hyphen but not a subcollection.

The database contains collections of documents, each document has it's own key-value pairs.
I assume you ment renaming a field in the collection and not an array inside a field.
So you can use the $rename operator to rename all fields in the collection
ex:
db.collectionName.update( {"A-Section": {$exists:true}}, {$rename: {"A-Section": 'ASection'} }, {multi: true} )

Related

Find all realted matched docs in an array of string

I have a mongoose schema model that have a field name tags , and it is an array of strings to store some tags in it for each document. I want something for example if I have an array of tags like ["test", "testimonials", "test Doc"] tags in it, when i search for test, it returns all documents with tags that they are testimonials or test doc , it should be work for example like wildcards (test*) .... can anyone help ?
this is the model
tags: {
type: [
{
type: String,
},
],
},
First of all, I'd tweak the Schema if possible. Your schema could be changed to this:
tags: [String]
This also just means an array of strings. You don't need to always need to use/specify the type key unless you're planning to add more fields to the tag schema, but it doesn't look like it from the question.
You can do the following to select all documents with a specific tag. Since I don't know what the name of your model is, I'll just call it "Model".
await Model.find({ tags: "tagName" })
OR
await Model.find({ tags: { $elemMatch: { someKey: someValue } } })
The later is only if you have other mongodb documents inside the array. Since you only have strings in the array, use the first method.

Node JS - Big Query insert to a Struct data type

Supposed I have a field "student" with a record type how or what should be the format of my json object if I would insert into a field with a record/struct type.
Would it be something like this?
{
student: {
name: 'John Doe',
age: 23
}
}
according here https://github.com/googleapis/nodejs-bigquery/blob/master/samples/insertRowsAsStream.js I would pass an object or array of objects to insert something to big query but I can't find an example that inserts into a record type
From the look at the repo, remove the student part, use student as the table name instead.
So it's just the object of student, or array of student objects.
Record type = table or even dataset.
You can insert RECORD type fields by enclosing their subfields with curly brackets {}, just like in your example.
In order to insert REPEATED fields, you would have to enclose them within square brackets [].
I hope this answers your question!

Mongodb E11000 duplicate key error on array field

I have a quick question about mongoose schema real quick. Here is the code: https://i.ibb.co/Db8xPMw/5555.png
I tried to create a document without the property "work". It works in the first time, but it didn't start to work on the second time that I do the same thing again.
Do you have any idea?
Basically I create two documents without an "work" property, which causes a duplicate key error. However, I didn't set up unqiue: true though.
Error :
"errmsg" : "E11000 duplicate key error collection: test.user index work_1 dup key: { : null }
From the message it says your collection has an index with name work_1 probably on field work, Since you've created a document without work field then basically you cannot create another document without work field what so ever in the same collection, cause two documents with no work field or even work field with value as null or same cannot exist as it violates unique constraint policies (it says dup key : { : null}) !! Uniques indexes can be created via mongoose schemas or can also be created by manually running queries on database.
Ref : Search for Unique Index and Missing Field in index-unique
So you need to drop the existing index using dropIndex & then if needed recreate it using createIndex. MongoDB would automatically convert a created index to index-multikey (multi-key index - indexes on array fields) if at least one existing document has array value for that indexed field by the time you create index or even if an array value gets inserted for that field in future.
Through code - Drop index : yourSchema.dropIndex({yourFieldName: 1}) && Create index : yourSchema.index({yourFieldName : 1})
NOTE : Just in case if you want to have certain criteria in unique indexes like situation from this question where indexed field can be missing in some documents but it shouldn't be considered as duplicate insertion, then you can take use of partial-indexes (Search for Partial Index with Unique Constraint) which would only index documents where work field exists.
Ex of partial-indexes :-
db.yourCollectionName.createIndex(
{ work: 1 },
{ unique: true, partialFilterExpression: { work: { $exists: true } } }
)
Ref : mongoose-Indexes

mongoose - avoid duplicate when all fields are equal to new entry

so I have a mongoose schema in my node application with two fields: tag and task, and I want to be able to save entries where the combination of both properties doesnt exist yet.
For example: my DB already has the following entries:
{tag:tag1, task:task1}
{tag:tag1, task:task2}
{tag:tag2, task:task1}
I want to be able to create {tag:tag2, task:task2}, but not {tag:tag1, task:task1} again, so I guess I cant use primary or unique in any of those fields, since they can repeat, except when their combination already exists
so which query should I use to save? Or should I find if it already exists first?
Use Unique Compound Indexing
db.users.createIndex( { "tag": 1, "task": 1 }, { unique: true } )
For more info visit the Link

Idempotency in MongoDB nested array, possible?

I am writing a REST api which I want to make idempotent. I am kind of struggling right now with nested arrays and idempotency. I want to update an item in product_notes array in one atomic operation. Is that possible in MongoDB? Or do I have to store arrays as objects instead (see my example at the end of this post)? Is it for example possible to mimic the upsert behaviour but for arrays?
{
username: "test01",
product_notes: [
{ product_id: ObjectID("123"), note: "My comment!" },
{ product_id: ObjectID("124"), note: "My other comment" } ]
}
If I want to update the note for an existing product_node I just use the update command and $set but what if the product_id isn't in the array yet. Then I would like to do an upsert but that (as far as I know) isn't part of the embedded document/array operators.
One way to solve this, and make it idempotent, would be to just add a new collection product_notes to relate between product_id and username.
This feels like violating the purpose of document-based databases.
Another solution:
{
username: "test01",
product_notes: {
"123": { product_id: ObjectID("123"), note: "My comment!" },
"124": { product_id: ObjectID("124"), note: "My other comment" } }
}
Anyone a bit more experienced than me who have anything to share regarding this?
My understanding of your requirement is that you would like to store unique product ids (array) for an user.
You could create an composite unique index on "username" and "username.product_id". So that when the same product id is inserted in the array, you would an exception which you could catch and handle in the code as you wanted the service to be Idempotent.
In terms of adding the new element to an array (i.e. product_notes), I have used Spring data in which you need to get the document by primary key (i.e. top level attribute - example "_id") and then add a new element to an array and update the document.
In terms of updating an attribute in existing array element:-
Again, get the document by primary key (i.e. top level attribute -
example "_id")
Find the correct product id occurrence by iterating the array data
Replace the "[]" with array occurrence
product_notes.[].note

Categories