Update mongo collection with values from a javascript map - javascript

I have a collection that looks like this
[
{
"project":"example1",
"stores":[
{
"id":"10"
"name":"aa",
"members":2
}
]
},
{
"project":"example2",
"stores":[
{
"id":"14"
"name":"bb",
"members":13
},
{
"id":"15"
"name":"cc",
"members":9
}
]
}
]
I would like to update the field members of the stores array taking getting the new values from a Map like for example this one
0:{"10" => 201}
1:{"15" => 179}
The expected result is:
[
{
"_id":"61",
"stores":[
{
"id":"10"
"name":"aa",
"members":201
}
]
},
{
"_id":"62",
"stores":[
{
"id":"14"
"name":"bb",
"members":13
},
{
"id":"15"
"name":"cc",
"members":179
}
]
}
]
What are the options to achieve this using javascript/typescript?

In the end, I resolved by updating the original database entity object with the values in the map, then I have generated a bulk query.
for (let p of projects) {
for(let s of p.stores) {
if(storeUserCount.has(s.id)){
s.members = storeUserCount.get(s.id);
}
};
bulkQueryList.push({
updateOne: {
"filter": { "_id": p._id },
"update": { "$set": {"stores": p.stores} }
}});
};
await myMongooseProjectEntity.bulkWrite(bulkQueryList);

You can use update() function of Mongoes model to update your expected document.
Try following one:
const keyValArray= [{"10": 201},{"15":"179"}];
db.collectionName.update({_id: givenId},
{ $push: { "stores": {$each: keyValArray} }},
function(err, result) {
if(err) {
// return error
}
//return success
}
});

Related

updateMany mongoose with multiple condition

I have two documents as in db bookingDetails" as:
{
"_id":ObjectId("12jj21jan21jdo3kan2idm11"),
"book_status":"BOOKED",
"reservation":false,
}
{
"_id":ObjectId("12jj21jan21jdo3kan2idm11"),
"book_status":"ACCEPTED",
"reservation":true,
}
update both of the document with multiple queries.
I am trying as,
bookingDetails.updateMany(
{
"book_status":"ACCEPTED",
},
{
$set:{
"book_status":"DONE"
}
}
)
bookingDetails.updateMany(
{
"book_status":"BOOKED",
},
{
$set:{
"book_status":"DONE"
}
}
)
But this method is repetitive which increases load on db. Is there any way that it can be optimized?
Please let me know if anyone needs any further information.
You can use an $or like this:
bookingDetails.updateMany({
"$or": [
{
"book_status": "ACCEPTED"
},
{
"book_status": "BOOKED"
}
]
},
{
"$set": {
"book_status": "DONE"
}
})
Example here

How to add a MongoDB match argument if it comes from frontend and not add any argument if it doesn't?

I am creating an aggregation in MongoDB using NodeJS. When the resolver function is called with an argument, I want it to be added to MongoDB match function and if it doesn't exist, then there will be no addition. The problem I am facing is that if there is no addition, no results are coming and if there is addition then the query is not coming properly. It is coming like this: phaseMatch = 'phase': { $in: CAT,MOD }. how do I make it come like phaseMatch = 'phase': { $in: ['CAT','MOD'] }? Is there any way to do this conditional only in the MongoDB aggregation and not use any JS?
async WeeklyTable(_, { batchSize, phase }) {
let res = [];
let phaseMatch = "";
if(phase) phaseMatch = "'phase': { $in: " + phase + " }";
return await collection.aggregate([{
$match: {
"segment": {
$exists: true,
$ne: null
},
phaseMatch
}
}];
}
There are many ways to dynamically build a query condition, here is a quick example:
async WeeklyTable(_, { batchSize, phase }) {
const res = [];
const matchCond = {
"segment": {
$exists: true,
$ne: null
},
}
if(phase) {
matchCond.phase = {$in: phase}
};
return await collection.aggregate([{
$match: matchCond
}];
}
Not sure exactly what you're trying to do with creating it as a string, the Mongo driver doesn't parse string arguments as query conditions.
EDIT
Without any javascript you could do:
db.collection.aggregate([
{
$match: {
"segment": {
$exists: true,
$ne: null
},
$expr: {
"$setIsSubset": [
[
"$phase"
],
{
$ifNull: [
phase,
[
"$phase"
]
]
}
]
}
}
}
])

Logic App/JavaScript - Remove Matching Values

I have two data sources. Data Source 1 is basically a list of Projects and Users assigned to those Projects. Data Source 2 is a list of Users that I want to remove from the Projects in Data Source 1.
Data Source 1:
[
{
"db1Project":[
{
"projectCode":"1",
"assignment":{
"db1User":[
{
"assignee":"wantzc"
},
{
"assignee":"michelles"
}
]
}
},
{
"projectCode":"2",
"assignment":{
"db1User":[
{
"assignee":"stallinga"
},
{
"assignee":"domanl"
},
{
"assignee":"brantleyd"
}
]
}
},
{
"projectCode":"3",
"assignment":{
"db1User":[
{
"assignee":"cinnamonk"
}
]
}
}
]
}
]
I want to match "assignee" from Data Source 1 with "sponsor" in Data Source 2.
Data Source 2:
[
{
"db2Users":[
{
"sponsor":"wantzc"
},
{
"sponsor":"patem"
},
{
"sponsor":"stallinga"
},
{
"sponsor":"oliviaa"
},
{
"sponsor":"brantleyd"
}
]
}
]
Then remove non-matching "assignee" and generate below output:
Desired Output:
[
{
"db1Project":[
{
"projectCode":"1",
"assignment":{
"db1User":[
{
"assignee":"wantzc"
}
]
}
},
{
"projectCode":"2",
"assignment":{
"db1User":[
{
"assignee":"stallinga"
},
{
"assignee":"brantleyd"
}
]
}
}
]
}
]
Can this be done using Logic App only? If not, how to do this using JavaScript?
This is a little bit of a verbose way to do it in Javascript, but the idea is relatively simple:
Create a map of the users you're looking for so you have an O(1) lookup instead of O(n) lookup each time
Filter the users list for each project to only contain users found in the db2Users list
Add the project to the new results set if any db1Users remain after step 2
This will take 1 pass through your original array, so it's an efficient, yet simple algorithm to do what you're trying to do.
let data = [{"projectCode":"1","assignment":{"db1User":[{"assignee":"wantzc"},{"assignee":"michelles"}]}},{"projectCode":"2","assignment":{"db1User":[{"assignee":"stallinga"},{"assignee":"domanl"},{"assignee":"brantleyd"}]}},{"projectCode":"3","assignment":{"db1User":[{"assignee":"cinnamonk"}]}}];
let db2Users = [{"sponsor":"wantzc"}, {"sponsor":"patem"}, {"sponsor":"stallinga"}, {"sponsor":"oliviaa"}, {"sponsor":"brantleyd"}];
let db2UsersMap = db2Users.reduce((res, curr) => {
res[curr.sponsor] = true;
return res;
}, {});
let filteredProjects = data.reduce((res, project) => {
let currProjUsers = project.assignment.db1User;
project.assignment.db1User = currProjUsers.filter((user) => db2UsersMap[user.assignee]);
if (project.assignment.db1User.length > 0) { res.push(project); }
return res;
}, []);
console.log(filteredProjects);

PouchDB emit object from an array of objects

I would like to search trough an array of objects (that are encapsulated in one big object), and emit only the one of the internal objects. So let's suppose I have a JSON inserted into PouchDB that is looks like this:
{
"_id": "5eaa6d20-2019-44e9-8aba-88cfaf8e02542",
"data": [
{
"id": 1452,
"language": "java"
},
{
"id": 18787453,
"language": "javascript"
},
{
"id": 145389721,
"language": "perl"
}
]
}
How to get PouchDB to return the following result when searching for a language with an id = 145389721:
{
"id": 145389721,
"language": "perl"
}
Thanks!
In the scenario above the easiest way, using typescript, is to write a temp query:
db.query((doc, emit) => {
for (let element of doc.data) {
if (element.id === 145389721) {
emit(element);
}
}
}).then((result) => {
for (let row of result.rows) {
console.log(row.key);
}
})
Using permanent queries it would have looked like this:
let index = {
_id: '_design/my_index',
views: {
"by_id": {
"map": "function(doc) {for (let element of doc.data) {emit(element.id, element); }}"
}
}
};
// save it
this.db.put(index).catch(error => {
console.log('Error while inserting index', error);
});
//query it
this.db.query('my_index/by_id', { startkey: 145389721, endkey: 145389721}).then(result => {
for (let row of result.rows) {
console.log(row.value);
}
}).catch(error => {
console.log('Error while querying the database with an index', error);
});

Missing Children

Using Mongoose with MongoDB, my Schema is as follows:
var PartSchema = new Schema({
partcode: String,
children: [String]
});
And the data looks like the following:
[{"partcode":"A1","children":["B1","B2","B3","B4"]},
{"partcode":"B1","children":["C11","C21","C31","C41"]},
{"partcode":"B3","children":["C13","C23","C33","C43"]},
I can query for A1's children field by using the following static call:
PartSchema.static('getChildren', function (partcode, callback) {
var self = this;
self.findOne({ partcode: partcode }, childrenOnly)
.exec(function (err, doc) {
return self.find({"partcode": {"$in": doc.children} }, exclId, callback);
});
});
This returns (via express)
[{"partcode":"B1","children":["C11","C21","C31","C41"]},
{"partcode":"B3","children":["C13","C23","C33","C43"]}]
What I need is to return all children not found, for example:
[{"children":["B2","B4"}]
You could use the _.difference() method from the lodash library to calculate the array set difference:
var _ = require("lodash");
PartSchema.static('getChildren', function (partcode, callback) {
var self = this;
self.findOne({ partcode: partcode }, childrenOnly)
.exec(function (err, doc) {
var promise = self.find({"partcode": {"$in": doc.children} }, exclId).lean().exec();
promise.then(function (res){
var codes = res.map(function (m) {
return m.children;
}),
obj = {"children": _.difference(doc.children, codes)},
result = [];
result.push(obj);
return result;
});
});
});
-- UPDATE --
With MongoDB's aggregation framework, you can achieve the desired result. Let's demonstrate this in mongoshell first.
Suppose you insert the following test documents in the parts collection:
db.part.insert([
{"partcode":"A1","children":["B1","B2","B3","B4"]},
{"partcode":"B1","children":["C11","C21","C31","C41"]},
{"partcode":"B3","children":["C13","C23","C33","C43"]}
])
The aggregation can be useful here given that you have an array of the children partcodes for a given partcode, say "A1", which is ["B1","B2","B3","B4"]. In this instance, your aggregation pipeline would consist of the following aggregation pipeline stages:
$match - You need this to filter those documents whose children partcodes are not in the ["B1","B2","B3","B4"] array. This is achieved using the $nin operator.
$group - This groups all the documents from the previous stream and creates an additional array field that has the parent partcodes. Made possible by using the $addToSet accumulator operator.
$project - Reshapes each document in the stream by adding a new field partcode (which will eventually become part of the result object) and suppresses the _id field. This is where you can get the array difference between the parent partcode in the criteria and those not in the pipeline documents, made possible using the $setDifference set operator.
Your final aggregation operator would look like this (using mongoshell):
var children = ["B1","B2","B3","B4"];
db.part.aggregate([
{
"$match": {
"children": { "$nin": children }
}
},
{
"$group": {
"_id": null,
"parents": {
"$addToSet": "$partcode"
}
}
},
{
"$project": {
"_id": 0,
"partcode": {
"$setDifference": [ children, "$parents" ]
}
}
}
]).pretty()
Output:
/* 0 */
{
"result" : [
{
"partcode" : ["B2","B4"]
}
],
"ok" : 1
}
Using the same concept in your Mongoose schema method:
PartSchema.static('getChildren', function (partcode, callback) {
var self = this;
self.findOne({ partcode: partcode }, childrenOnly)
.exec(function (err, doc) {
var pipeline = [
{
"$match": {
"children": { "$nin": doc.children }
}
},
{
"$group": {
"_id": null,
"parents": {
"$addToSet": "$partcode"
}
}
},
{
"$project": {
"_id": 0,
"partcode": {
"$setDifference": [ doc.children, "$parents" ]
}
}
}
],
self.aggregate(pipeline).exec(callback);
});
});
Or using Mongoose aggregation pipeline builder for a fluent call:
PartSchema.static('getMissedChildren', function (partcode, callback) {
var self = this;
self.findOne({ partcode: partcode }, childrenOnly)
.exec(function (err, doc) {
var promise = self.aggregate()
.match({"children": { "$nin": doc.children }})
.group({"_id": null,"parents": {"$addToSet": "$partcode"}})
.project({"_id": 0,"partcode": {"$setDifference": [ doc.children, "$parents" ]}})
.exec(callback);
});
});

Categories

Resources