(AQL) how to INSERT more than one document INTO a collection - arangodb

according to ArangoDB documentation, INSERT operation is applicable for a single document insertion. I have an array which may have thousands of objects (documents). Is there a way to INSERT this array of document INTO a collection with a single query?

I believe you've misunderstood the documentation, which says:
Only a single INSERT statement per collection is allowed per AQL query
You can have multiple INSERT statements per AQL query (subject to the above limitation, amongst others), and each of them can entail multiple insertions.
Here's an example of 1000 insertions executed successfully as one AQL query:
FOR n in 1..1000
INSERT {_from: "tasks/1", _to: CONCAT("tasks/", TO_STRING(n))} in depends
COLLECT WITH COUNT INTO c
RETURN c

Another approach would be to access the database with arangosh:
You can use the method collection.insert(array) to insert an array consisting of multiple documents into a collection.
Example: Insert two documents into the collection "example"
db.example.insert([{ id : "doc1" }, { id : "doc2" }]);
[
{
"_id" : "example/12156601",
"_key" : "12156601",
"_rev" : "_WEnsap6---"
},
{
"_id" : "example/12156605",
"_key" : "12156605",
"_rev" : "_WEnsap6--_"
}
]
The method is documented at: https://docs.arangodb.com/3.2/Manual/DataModeling/Documents/DocumentMethods.html

BULK Insert in AQL v3.6 is as following:
db.collection('collection_name').save([{ id : "doc1" }, { id : "doc2" }]);
as described in docs and I have tested it in my project using NodeJS.
https://www.arangodb.com/docs/stable/programs-arangosh-details.html#database-wrappers

Related

MongoDb Insert many not working with ordered false option in transaction

I am creating a collection blog with the following unique index:
{
"title" : 1,
"author" : 1
}
unique:true
This collection consists the following document
{
"title":"Java",
"author":"ABC",
code:123
}
Now I want to insert the following document into it
[{
"title":"JAVA",
"author":"ABC",
code:234
}]
I am using insertMany query to add this to the collection. but the collection has a unique index. so when I try to insert the above document in the collection it will give an error like the title is not unique. but I want check other field error also here so I am using insertMany query with ordered option like:
db.insertMany("blog",[{
"title":"JAVA",
"author":"ABC",
code:234
}]
, {ordered: false})
the above query error gives me all two field names. but when I am trying to use this with Mongodb transaction it will gives only one field error I am using Transaction like:
let session = await db.startSession({});
db.insertMany("blog",[{
"title":"JAVA",
"author":"ABC",
code:234
}]
, {ordered: false, session})
SO how I get all fields name in result whose no unique using insertMany, ordered, and session? Kindly help me here

CosmosDb Mongo - collection with shardkey, slow query by shardkey?

I have a CosmosDb collection with Mongodb.
This is a customer database, and the ShardKey is actually CustomerId.
My collection has 200000 records, and has an combined index of both e-mail and customerid.
An example of a customer:
{
"CustomerId" : "6a0f4360-d722-4926-9751-9c7fe6a97cb3",
"FirstName" : "This is my company first name",
"LastName" : "This is my company last name",
"Email" : "6a0f4360-d722-4926-9751-9c7fe6a97cb3#somemail.com",
"Addresses" : [
{
"AddressId" : "54e34da9-55fb-4d60-8411-107985c7382e",
"Door" : "11111",
"Floor" : "99",
"Side" : "B",
"ZipCode" : "8888",
}
]
}
What I find strange is if I query by Email it spends 7000RUs (which is too much - at least is what data explorer tells me...) but if I query by CustomerId, it spends more or less the same RUs...
My questions are:
Shoudn't both operations spend less RUs than this, specially by CustomerId?
An example of a query by E-mail:
{ "Email" : { $eq: "3f7da6c3-81bd-4b1d-bfa9-d325388079ab#somemail.com" } }
An example of a query by CustomerId:
{ "CustomerId" : { $eq: "3f7da6c3-81bd-4b1d-bfa9-d325388079ab" } }
Another question, my index contains both Email and CustomerId. Is there any way for me to query by e-mail and return only CustomerId, for example?
Shoudn't both operations spend less RUs than this, specially by CustomerId?
CustomerId is your shard key (aka partition key) which helps in grouping documents with same value of CustomerId to be stored in the same logical partition. This grouping is used during pin-point GET/SET calls to Cosmos but not during querying. So, you would need an index on CustomerId explicitly.
Furthermore, since the index that you have is a composite index on CustomerId and Email, doing a query on only one of these fields at a time will lead to a scan being performed in order to get back the result. Hence the high RU charge and the similar amount of RU charge on each of these queries.
Another question, my index contains both Email and CustomerId. Is there any way for me to query by e-mail and return only CustomerId, for example?
Firstly, in order to query optimally on Email, you would need to create an index on Email separately. Thereafter, you may use the project feature of Mongo to include only certain fields in the response.
Something like this-
find({ "Email" : { $eq: "3f7da6c3-81bd-4b1d-bfa9-d325388079ab#somemail.com" } }, { "CustomerId":1 })

MongoDB - Use results of multiple fetch queries in one update query

I am building a platform for students to give mock test on. Once the test is complete, a results are to be generated for them relative to other students who attempted the said test.
Report contains multiple parameters i.e. rank, rank within their batch, and stuff like average marks people got on the given test are updated.
To get each of this data, I need to perform a separate query on the database and then I got to update 1. the result of current user who attempted the test 2. the result of everyone else (i.e. everyone's rank changes on new attempts)
So I need to perform multiple queries to get the data and run 2-3 update queries to set the new data.
Given mongodb calls are asynchronous, I can't find a way to gather all of that data at one place to be updated.
One way is to put the next query within the callback function of the previous query but I feel like there should be a better way than that.
Maybe you could use Promise.all()
Example:
const initialQueries = []
initialQueries.push("Some promise(s)")
Promise.all(initialQueries).then(results => {
// After all initialQueries are finished
updateQueries()
}).catch(err => {
// At least one failed
})
Use db.collection.bulkWrite.
It allows multiple document insertions, updates (by _id or a custom filter), and even deletes.
const ObjectID = require('mongodb').ObjectID;
db.collection('tests').bulkWrite([
{ updateOne : {
"filter" : { "_id" : ObjectID("5d400af131602bf3fa09da3a") },
"update" : { $set : { "score" : 20 } }
}
},
{ updateOne : {
"filter" : { "_id" : ObjectID("5d233e7831602bf3fa996557") },
"update" : { $set : { "score" : 15 } }
}
}
]);
New in version 3.2.

Query documents in an array in mongodb using node.js

How to query all documents present inside an Array which itself is present in a MongoDB collection under Node.js.
For example: I have a DB with a structure:
{
"name1":[{"height":"5.5"},
{"weight":"57"}],
"name2":[{"height":"6.1"},
{"weight":"74"}]
}
What query should I make to get all the documents( i.e. height, weight) of the array "name1"
Output should be :
{
{ "height":"5.5"}
{"weight":"57"}
}
My suggestion would be to reorganise the collection so each document has a key of name and key of physicalattributes e.g.
{
'name' : 'name1',
'physAttr': ['height': heightvalue,
'weight': weightvalue]
}
then suppose you wanted to find all documents with height 5.5, the query would be trivial
db.collection.find({ 'physAttr.height': 5.5 })
As described in the question each document in the collection has a different schema from the others (different name key for every document) making query operations difficult.

How to update one field if the document exist in a collection using mongodb and nodejs?

I am new dealing with mongodb, I read a set of identified documents from one source time to time. I save the documents to a collection using "_id" field to avoid repetition.
I want to add the documentos to the new documents, but if any documento exist, I want to update a field of the documento (in this case, increase a value like a counter).
I would to ask if there are a easy way to do this in mongodb.
Make of use upsert with update query.
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>
}
)
db.students.update(
{ "_id" : "1" },
{ "$set" : { "name" : "Hiren" } },
{ "upsert" : true }
);
if student with id 1 doesnot exists it will add new document with id 1 and name hiren. and if document exists with _id 1, then updates its name to Hiren.

Resources