Access title inside id - javascript

I am having trouble to access title inside an ID object.
I want to access item.title. But i am not able to give a name to the object ID.
I tried doing order.cart.items.item.title
"_id" : ObjectId("5d60d1752cda6403e4f868af"),
"created_at" : ISODate("2019-08-24T05:55:34.741Z"),
"user" : ObjectId("5d60d00e4c865312ccf3f18a"),
"cart" : {
"items" : {
"5d60cddb69f460191c680e96" : {
"item" : {
"_id" : "5d60cddb69f460191c680e96",
"imagePath" : "https://dks.scene7.com/is/image/GolfGalaxy/18NIKWRMX270XXXXXLFS_Black_Cream?wid=1080&fmt=jpg",
"title" : "Nike ",
"description" : "Nike Airmax",
"price" : 10,
"category" : "shoes",
"__v" : 0
},
"qty" : 1,
"price" : 10
}
},
"totalQty" : 1,
"totalPrice" : 10
},

You need to use Object.values for that, because of the ID. This allows you to get the object with the key of 5d60cddb69f460191c680e96 without the key:
Object.values(order.cart.items)[0].item.title

const data = {
"cart" : {
"items" : {
"5d60cddb69f460191c680e96" : {
"item" : {
"_id" : "5d60cddb69f460191c680e96",
"imagePath" : "https://dks.scene7.com/is/image/GolfGalaxy/18NIKWRMX270XXXXXLFS_Black_Cream?wid=1080&fmt=jpg",
"title" : "Nike ",
"description" : "Nike Airmax",
"price" : 10,
"category" : "shoes",
"__v" : 0
},
"qty" : 1,
"price" : 10
}
},
"totalQty" : 1,
"totalPrice" : 10
}};
for (let id in data.cart.items)
console.log(data.cart.items[id].item.title);

You can simply achieve this by getting key name of an object using Object.keys() methods, This methods returns an array of key names
const obj = { id: 1 };
const keysArray = Object.keys(obj);
console.log(keysArray);. // ["id"]
In your case only one keys are present in the object, So we can directly get that name with index 0 (Object.keys(obj)[0])
Check below snippet
const cart ={
"items": {
"5d60cddb69f460191c680e96": {
"item": {
"_id":
"5d60cddb69f460191c680e96",
"imagePath": '',
"title": "Nike ",
"description": "Nike",
"price": 10,
"category": "shoes",
"__v": 0
},
"qty": 1,
"price": 10
}
}
};
const id =
Object.keys(cart.items)[0];
console.log(
cart.items[id].item.title
);

Related

getBypage in Nested Array in MongoDB using Aggregate

I am using mongoDB as backend server, I have nested array(one level array) like this
{
"_id" : ObjectId("60b1fc6d3c43f74e0c1dba92"),
"seriesId" : "60acebf73acb5b3a98d14331",
"name" : "Season 1",
"logoURL" : "uploads/season/1622277216401.png",
"yearOfPublish" : "2021-05-29",
"description" : "Season 1",
"createdBy" : ObjectId("609cbf49ba46cc3924859ab5"),
"createdOn" : "2021-05-29T08:33:49.480Z",
"episode" : [
{
"seasonId" : "60b1fc6d3c43f74e0c1dba92",
"name" : "Episode 1",
"id" : 0,
"logoURL" : "uploads/episode/1622278616899.png",
"dateOfTelecast" : null,
"description" : "sadfgh",
"duration" : "30",
"videoType" : "customURL",
"embedCode" : "",
"url" : "https://youtu.be/kbpsXMUr7ss",
"liveboxChannel" : "",
"createdOn" : "2021-05-29T08:56:59.230Z",
"createdBy" : ObjectId("609cbf49ba46cc3924859ab5"),
"_id" : "ZaVrpOLO5"
},
{
"seasonId" : "60b1fc6d3c43f74e0c1dba92",
"name" : "Episode 2",
"id" : 0,
"logoURL" : "uploads/episode/1622279206607.png",
"dateOfTelecast" : null,
"description" : "adfd",
"duration" : "30",
"videoType" : "customURL",
"embedCode" : "",
"url" : "https://youtu.be/kbpsXMUr7ss",
"liveboxChannel" : "",
"createdOn" : "2021-05-29T09:06:48.637Z",
"createdBy" : ObjectId("609cbf49ba46cc3924859ab5"),
"_id" : "9GKqXhxcH"
},}
I have more no of seasons. from the season collection,i have episode array under the name of Episode.
Now My frontend page required that episode array alone.
response = {episode: all the episode data} and this episode data is based on skip and limit value
I have tried something in mongodb,
db.getCollection('season_copy').aggregate([
{$project: {
episodes: {
$cond:{ if: { $isArray: "$episode" }, then: { input:"$episode" }, else: 0 }
},
},
},
])
Can anyone suggest me some idea?
Check this out:
Without aggregate:
db.getCollection('season_copy')
.find({ _id: ObjectID(id)})
.project({ episode: 1 }).toArray();
With aggregate:
MongoDB playground
db.getCollection('season_copy')
.aggregate([
{
$match: {
_id: ObjectId("60b1fc6d3c43f74e0c1dba92")
}
},
{
$project: {
episode: 1
}
}
])

Array Iteration in typescript based on two values

This question might be a simple iteration, but I'm stuck in the logic.
I have an array of data which needs to be iterated based on id and code and remove the data only when the code is not present in the given id's.
Here is the Case Scenarios,
From the below data,
There are two different code named "GOOGLE" with different id - Valid Case
There are two different code named "FACEBOOK" with different id - Valid Case
There is a code named "TWITTER" which is not present in another id - INVALID Case.
Here, I wanted to remove this data based on case 3.
{
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}
Can someone help me with this scenario?
****Below is the original array data****
data = [ {
"id" : 381,
"code" : "GOOGLE",
"comment" : "ffff"
}, {
"id" : 381,
"code" : "FACEBOOK",
"comment" : "fff"
}, {
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}, {
"id" : 378,
"code" : "GOOGLE",
"comment" : "rferer"
}, {
"id" : 378,
"code" : "FACEBOOK",
"comment" : "fefehh"
} ]
I tried something below, but not sure how to proceed after this.
And, I'm using angular 7 and it will be helpful if I get the solution based on typescript.
this.data.forEach((row, index) => {
let value = row.id;
if(originalArray.indexOf(value) == -1) {
console.log(value);
}
originalArray.push(row);
})
try this:
data = [ {
"id" : 381,
"code" : "GOOGLE",
"comment" : "ffff"
}, {
"id" : 381,
"code" : "FACEBOOK",
"comment" : "fff"
}, {
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}, {
"id" : 378,
"code" : "GOOGLE",
"comment" : "rferer"
}, {
"id" : 378,
"code" : "FACEBOOK",
"comment" : "fefehh"
} ]
var result = data.reduce((unique, o) => {
if(data.filter(obj => obj.id != o.id && obj.code === o.code).length>=1) {
unique.push(o);
}
return unique;
},[]);
console.log(result);
Your logic that "Any code + Id pair that is not matched is removed" seems to directly contradict your first two cases, given that those pairs aren't matched - the ID is different.
Regardless, the code below will only keep items that have duplicate code with different id.
const data = [ { "id" : 381, "code" : "GOOGLE", "comment" : "ffff" }, { "id" : 381, "code" : "FACEBOOK", "comment" : "fff" }, { "id" : 378, "code" : "TWITTER", "comment" : "zeeer" }, { "id" : 378, "code" : "GOOGLE", "comment" : "rferer" }, { "id" : 378, "code" : "FACEBOOK", "comment" : "fefehh" } ];
let result = data.filter(({id,code}) => !!data.find(obj => obj.code === code && obj.id !== id));
console.log(result);
Optimally you wouldn't need nested array methods here, and rather a lookup/hashmap to prevent unnecessary iteration, but seeing that you already accepted an answer I'll forego that for now.
With Lodash
const data = [ {
"id" : 381,
"code" : "GOOGLE",
"comment" : "ffff"
}, {
"id" : 381,
"code" : "FACEBOOK",
"comment" : "fff"
}, {
"id" : 378,
"code" : "TWITTER",
"comment" : "zeeer"
}, {
"id" : 378,
"code" : "GOOGLE",
"comment" : "rferer"
}, {
"id" : 378,
"code" : "FACEBOOK",
"comment" : "fefehh"
} ];
const groupedData = _.groupBy(data, 'code'); // import * as _ from 'lodash'
console.log(data.filter(entry => groupedData[entry.code].length > 1));
Result:
[Object, Object, Object, Object]
0: Object
code: "GOOGLE"
comment: "ffff"
id: 381
__proto__: Object
1: Object
code: "FACEBOOK"
comment: "fff"
id: 381
__proto__: Object
2: Object
code: "GOOGLE"
comment: "rferer"
id: 378
__proto__: Object
3: Object
code: "FACEBOOK"
comment: "fefehh"
id: 378
__proto__: Object

How to get aggregation of child collection in mongodb and apply $count is not working

I want to sum counts values for each beacon. I'm using aggregate query but it returns with counts 0. Please let me know if there is mistake in query.
Sample Data
[ {
"_id" : ObjectId("5a8166392aa41ec66efc66bf"),
"userID" : "5a7c3410bdff0f0014181874",
"date" : ISODate("2018-02-08T11:04:54.000Z"),
"beacons" : [
{
"counts" : "2",
"UUID" : "red"
},
{
"counts" : "1",
"UUID" : "blue"
}
]
},
{
"_id" : ObjectId("5a8166392aa41ec66efc66c0"),
"userID" : "5a7c3410bdff0f0014181874",
"date" : ISODate("2018-02-08T11:04:54.000Z"),
"beacons" : [
{
"counts" : "2",
"UUID" : "red"
},
{
"counts" : "1",
"UUID" : "blue"
}
]
}
]
Query
/* Query */
db.getCollection('CountsDetail')
.aggregate([
{
"$unwind":"$beacons"
},
{
"$group": {
"_id":"$beacons.UUID", "counts":{ "$sum":"$counts"}
}
}]);
Response
/* Response */
{
"_id" : "red",
"counts" : 0
}
{
"_id" : "blue",
"counts" : 0
}
Response is returning 0 in sum, which is weird. Please correct what I am doing wrong. Thanks
Sorry miss read your OP. Your counts field is nested so use a dot notation:
"counts":{ "$sum":"$beacons.counts"}

how to use value as key in mongodb

Given this as output of mongo find command
{
"cust" : NumberInt(8388),
"key" : "T_SUB_CAT",
"value" : "98",
"tag1" : "T_RECENT_SUB_CAT_1"
},{
"cust" : NumberInt(8388),
"key" : "T_SUB_CAT",
"value" : "109",
"tag1" : "T_RECENT_SUB_CAT_2"
},{
"cust" : NumberInt(8388),
"key" : "T_SUB_CAT",
"value" : "6",
"tag1" : "T_RECENT_SUB_CAT_3"
}
how to use aggregation and $project to get result like this
{
"cust" : NumberInt(8388),
"T_RECENT_SUB_CAT_1" : "98",
"T_RECENT_SUB_CAT_2" : "109",
"T_RECENT_SUB_CAT_3" : "6"
}
please help me using project / aggregate
thanks a lot
put all result in a var say cust2,
while(cust2.hasNext()){
var document = cust2.next(); db.<collection>.update(
{ cust: document.cust, tag1:document.tag1 },
{ cust:document.cust , tag1:document.tag1 ,
key:document.key, value:document.value },
{upsert:true}
) }

mongodb update on JSON array

I have this data in Mongo:
{'_id':1,
'name':'Root',
'taskId':1,
'parentId':"",
'path':[1],
'tasks':[ {"taskId":3,parentId:1,name:'A',type:'task'},
{"taskId":4,parentId:1,name:'D',type:'task'},
{"taskId":5,parentId:4,name:'B',type:'task'},
{'type':'project' , 'proRef':2},
{"taskId":6,parentId:3,name:'E',type:'task'},
{"taskId":7,parentId:6,name:'C',type:'task'}]
}
Now I want to update taskId 6 with new Json data .
var jsonData = {"taskId":6,"name":'Sumeet','newField1':'Val1','newField2':'Val2'}
query should update if field is available else add new key to existing .Output Like
{"taskId":6,parentId:3,name:'Sumeet',type:'task','newField1':'Val1','newField2':'Val2'}]
I have tried few query but it is completely replacing json .
db.projectPlan.update({_id:1,'tasks.taskId':6},{$set :{'tasks.$':jsonData }});
Thanks in advance for your helps!
Sumeet
You need to transform the jsonData variable into something that can be passed to update. Here's an example that does exactly what you want with your sample document:
var updateData = {};
for (f in jsonData) {
if (f != "taskId") updateData["tasks.$."+f]=jsonData[f];
};
db.projectPlan.update({_id:1, 'tasks.taskId':6}, {$set:updateData})
Result:
{ "_id" : 1,
"name" : "Root",
"taskId" : 1,
"parentId" : "",
"path" : [ 1 ],
"tasks" : [
{ "taskId" : 3, "parentId" : 1, "name" : "A", "type" : "task" },
{ "taskId" : 4, "parentId" : 1, "name" : "D", "type" : "task" },
{ "taskId" : 5, "parentId" : 4, "name" : "B", "type" : "task" },
{ "type" : "project", "proRef" : 2 },
{ "taskId" : 6, "parentId" : 3, "name" : "Sumeet", "type" : "task", "newField1" : "Val1", "newField2" : "Val2" },
{ "taskId" : 7, "parentId" : 6, "name" : "C", "type" : "task" }
] }
You will need to merge the document manually:
var jsonData = {"taskId":5,"name":'Sumeet','newField1':'Val1','newField2':'Val2'};
db.projectPlan.find({ _id: 1 }).forEach(
function(entry) {
for (var taskKey in entry.tasks) {
if (entry.tasks[taskKey].taskId === jsonData.taskId) {
printjson(entry.tasks[taskKey]);
for (var taskSubKey in jsonData) {
entry.tasks[taskKey][taskSubKey] = jsonData[taskSubKey];
}
printjson(entry.tasks[taskKey]);
}
}
db.projectPlan.save(entry);
}
);
Obviously you can leave away the printjson statements. This is simply to see that the merging of the original tasks with the new tasks works. Note that this query will only update a single document as long as the _id field is unique.

Categories

Resources