n1ql query to remove data from array which has parameter value null - n1ql

Following is the sample document (userdetails) in couchbase.
{ "friends":[
{
"company":"microsoft",
"firstname":"criss",
"lastname":"angel"
},
{
"company":"google",
"firstname":"captain",
"lastname":null
} ] }
based on the company name, i want to remove the respective json document from the array.
n1ql query
update default use keys "userdetails" set friends=array_remove(friends,a) for a in friends when a.company="google" end returning friends
Im not able to remove the json data using the above query.
This query works properly, if we have empty string ( "lastname" : " ") rather than null value.
So, how to remove, if any of the parameter value is "null"

You can replace the whole friends array as follows:
UPDATE default
USE KEYS "userdetails"
SET friends = ARRAY a FOR a IN friends WHEN a.company <> "google" END
RETURNING friends;

Related

ravendb NodeJS, load related document and create a nested result in a query

I have an index that returns something like this
Company_All {
name : string;
id : string;
agentDocumentId : string
}
is it possible to load the related agent document and then generate a nested result with selectFields and QueryData like this
ICompanyView {
companyName : 'Warner',
user {
documentId : 'A/1'
firstName : 'john',
lastName : 'paul'
}
}
I need something like the below query that obviously doesn't work as I expect:
const queryData = new QueryData(
["name", "agentDocumentId", "agent.firstName", "agent.lastName"],
["companyName", "user.documentId", "user.lastName", "user.firstName"]);
return await session.query<Company_AllResult>({ index: Company_All })
.whereEquals("companyId", request.companyId)
.include(`agents/${agentDocumentId}`) // ????
.selectFields(queryData,ICompanyView)
.single();
Yes, you can do that using:
https://ravendb.net/docs/article-page/5.4/nodejs/indexes/indexing-related-documents
This is called indexing related documents, and is accessible at indexing time, not query time.
Alternatively, you have the filter clause, which has access to the loaded document, but I wouldn't generally recommend doing this.
Generally:
When you query an index, the results of querying the index are the documents from the collection the index was defined on.
Index-fields defined in the index are used to filter the index-query
but the results are still documents from the original collection.
If you define an index that indexes content from a related-document then when making an index-query you can filter the documents by the indexed-fields from the related documents, but the results are still documents from the original collection.
When making an index-query (or any other query) you can project the query results so that Not the full documents of the original collection are returned but some other object.
Now:
To project/get data from the indexed related-document you have 2 options:
Store the index-fields from the related-document in the index.
(Store all -or- specific fields).
This way you have access to that content when making a projection in your query.
See this code sample.
Don't store the index-fields from the related-document,
then you will be able to use the index-fields to filter by in your query,
but to get content you will need to use 'include' feature in your query,
and then use the session.load, which will Not make another trip to the server.
i.e. https://demo.ravendb.net/demos/nodejs/related-documents/query-related-documents

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

Querying a collection with matching IDs from an array of JSON objects with Mongoose

I have a database collection where each row has a unique ID associated with it. I want to be able to query my database and match data from it with the IDs in each of the objects from an array. The _ids are a string.
Collection Example:
"_id" : "453241",
"name" : "Item1",
"_id" : "621984",
"title" : "Item2",
"_id" : "832127",
"title" : "Item3",
The object would look something like this:
query = [{"_id":"621984","quantity":"3"},{"_id":"832127","quantity":"2"}]
The desired output would be something like this (I do not want to write to the database the quantity):
output = [{"_id":"621984","Item2", "quantity":"3"},{"_id":"832127", "Item3" ,"quantity":"2"}]
From the other threads, I read from what I understand we have to use the $is to match the data. Like the one in this example MongoDB select where in array of _id? However, the issue with this is that they are using an array of IDs. And I'm not sure how we would append the quantity to this value.
I also considered iterating through a loop of all of the objects inside of the array and then searching the database. And appending the output to an array. This would be most beneficial as I would want the overall output to include the quantity as well.
console.logging result in this case works and outputs the designated ID table however when attempting to append the values to output and then returning this does not work and returns an empty array.
output = []
for (item in query) {
collection.find({"id": item._id}).then((result) => { output.push(result + item.quantity) })
}
return output
Any ideas or help would be greatly appreciated thanks.
I've run into very similar situations with my own implementations as far as efficiency is concerned. The approach that I ended up taking (granted in a one-to-many relationship) is the following.
Isolate the Ids into an array prior to the Mongoose Query
let ids = []
for (object in query) {
ids.push(query[object]._id)
}
collection.find({ id : $in : ids }).then((result) => {
for (let i in result) {
for (let j in query) {
if (result[i]._id === query[j]._id) {
query[j].name = result[i].name
}
}
}
}).catch((error) => {
console.log("Query Error")
})
Also, in the above example, taking the array of Ids is going to require the Mongo $in operator to search through the array and return the appropriate collection items.
I hope this helps!

DynamoDB update inside an array of objects (nodejs)

I noticed that DynamoDB can add and remove items from an array but how do you search for an specific item inside an object if you want to update that one specifically?
For example:
In MongoDB you can search for someitem.$.subitem and update that specific item.
Is there a way on how to do this with DynamoDB?
Item: {
someitem: [
{
subitem: "id",
somevalue: "something"
}
]
}
I would say this is basic functionality but seems not easy to find (or even unsupported)
AWS does not permit to modify it in a single update request more info was found in the following answers:
updating-a-json-array-in-aws-dynamodb.
The solution that they propose is to change the schema from array to {}, or to implement a custom functions and iterate through each array and find your new id to update, so to speak to programatically update your json and then insert whole object.
TableName : 'tablename',
Key : { id: id},
ReturnValues : 'ALL_NEW',
UpdateExpression : 'set someitem['+`index`+'].somevalue = :reply_content',
ExpressionAttributeValues : { ':reply_content' : updateddata }
array element edit via array index

CouchDb view - key in a list

I Want to query CouchDB and I have a specific need : my query should return the name field of documents corresponding to this condition : the id is equal or contained in a document filed (a list).
For example, the field output is the following :
"output": [
"doc_s100",
"doc_s101",
"doc_s102",
"doc_s103",
],
I want to get all the documents having in their output field "doc_s102" for example.
I wrote a view in a design document :
"backward_by_docid": {
"map": "function(doc) {if(doc.output) emit(doc.output, doc.name)}"
}
but this view works only when I have a unique value in the output field.
How can I resolve this query ?
Thanks !
you have to iterate over the array:
if(doc.output) {
for (var curOutput in doc.output) {
emit (doc.output[curOutput],doc.name);
}
}
make sure that output always is an array (at least [])
.. and, of course use key="xx" instead key=["xxx"]

Resources