How do I get a nested object from a selected document?
If this is my document, which I get with Collection.findOne({ _id: 'dZXr2Pg7Ak4M5aYWF'})...
{
"_id" : "dZXr2Pg7Ak4M5aYWF",
"points" : [
{
"id" : "Gwf5BzorXyYBZSEzK",
"coordinates" : [
433,
215
],
"content" : "anything"
},
{
"id" : "iwSM98W5PD87BtcLa",
"coordinates" : [
666,
186
]
}
]
}
... I need to get the complete data of the point with the id Gwf5BzorXyYBZSEzK. So my result should look like:
result = {
"id" : "Gwf5BzorXyYBZSEzK",
"coordinates" : [
433,
215
],
"content" : "anything"
}
You can simply filter the points array, with Array.prototype.filter, like this
console.log(data.points.filter(function(obj) {
return obj.id === "Gwf5BzorXyYBZSEzK";
})[0]);
// { id: 'Gwf5BzorXyYBZSEzK' coordinates: [ 433, 215 ], content: 'anything' }
We just take the first element from the filtered result array. If you want to get all the elements, which have the specific id, then just remove the subscript.
If your environment supports ECMAScript 2015's Arrow functions, then you can write the same as
console.log(data.points.filter((obj) => obj.id === "Gwf5BzorXyYBZSEzK")[0]);
var data = {
"_id": "dZXr2Pg7Ak4M5aYWF",
"points": [{
"id": "Gwf5BzorXyYBZSEzK",
"coordinates": [433, 215],
"content": "anything"
}, {
"id": "iwSM98W5PD87BtcLa",
"coordinates": [666, 186]
}]
};
function finder(id){
for(i=0;i<data.points.length;i++){
if(data.points[i].id==id){
return data.points[i];
}
}
}
var result = finder("Gwf5BzorXyYBZSEzK");
document.write(JSON.stringify(result));
Related
I'm trying to get all the values(which are arrays) of the "coordinate" type in my data like that:
[
["51.50064317423898","-0.09372711181640626"],
["51.48465408363687","-0.13149261474609378"]
]
I tried db.collections("mydb").distinct("coordinate") but i get:
[
'-0.09372711181640626',
'-0.13149261474609378',
'51.48465408363687',
'51.50064317423898'
]
Does anyone have an idea how i can just have all my arrays like i want and not ordered in one array?
"mydb" looks like this:
{
"name":"dfbfdbf",
"coordinate":["51.50064317423898","-0.09372711181640626"],
"rating":"8",
"description":"geojzglijsen"
},
{
"name":"qzfgs",
"coordinate":["51.48465408363687","-0.13149261474609378"],
"rating":"5",
"description":"femkndsmnk"
}
Thank you!
If I've understood correctly you can try this aggregate query:
The point is $group by null to get all values and use $addToSet which prevents the duplicates values.
db.collection.aggregate([
{
"$group": {
"_id": null,
"coordinate": {
"$addToSet": "$coordinate"
}
}
},
{
"$project": {
"_id": 0
}
}
])
Example here where I've duplicated one object to see how the repeated value is not displayed.
If you need to fetch distinct coordinates from your collection:
mongos> db.a.find()
{ "_id" : ObjectId("619ea12e032deead586f3f91"), "name" : "dfbfdbf", "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea138032deead586f3f92"), "name" : "a", "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea14c032deead586f3f93"), "name" : "a", "coordinate" : [ "51.50064317423898", "-0.19372711181640626" ] }
{ "_id" : ObjectId("619ea157032deead586f3f94"), "name" : "a", "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea15b032deead586f3f95"), "name" : "a", "coordinate" : [ "52.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea160032deead586f3f96"), "name" : "a", "coordinate" : [ "52.50064317423898", "-0.09372711181640626" ] }
mongos> db.a.aggregate([
{ $addFields:{coordinates:{$reduce:{ input: {$slice:["$coordinate",1,{$size:"$coordinate"} ]},initialValue:{$arrayElemAt:["$coordinate",0]},in:{$concat:["$$value",";","$$this" ]} }} }} ,
{ $group:{_id:"$coordinates" , cnt:{$sum:1}}} ,
{ $project : { coordinate : { $split: ["$_id", ";"] } ,_id:0}}
])
{ "coordinate" : [ "51.50064317423898", "-0.19372711181640626" ] }
{ "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "coordinate" : [ "52.50064317423898", "-0.09372711181640626" ] }
mongos>
Example:
here
explained:
Remove duplicate coordinates from collection
create new field coordinates where you join the coordinates in single string
group the coordinates to remove duplicates
split the coordinates to the original values.
This solution has no limitation of distinct coordinates array summary size of 16MB as well ...
I have an object that is structured similar as follows (simplified version):
{
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{
"id" : 123,
"name": "test123"
},
{
"id" : 123,
"name": "test4554"
}
]
}
}
How do I use lodash ._uniqBy to deduplicate the results, based on results.results.id being the unique key?
To clarify, I would like the deduplicated resultset to be returned within the original object structure, e.g.
{
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{
"id" : 123,
"name": "test123"
}
]
}
}
thanks
You can achieve your goal by simply passing the right part of your object into _.uniqBy(array, [iteratee=_.identity]) function.
Next thing you want to do is to 'concat' lodash uniqBy result and your object. This is a little bit tricky. I suggest you to use ES6 Object.assign() method and spread operator.
Check out my solution. Hope this helps.
const myObj = {
"time": 100,
"complete" : true,
"results" : {
"total": 10,
"score": 3,
"results": [
{"id" : 123, "name": "test123"},
{"id" : 123, "name": "test4554"}
]
}
};
const uniq = _.uniqBy(myObj.results.results, 'id');
const resultWrapper = Object.assign({}, myObj.results, { results: [...uniq] });
const resultObj = Object.assign({}, myObj, { results: resultWrapper });
console.log( resultObj );
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.5/lodash.min.js"></script>
You can use something like this
const myObj = {
time: 100,
complete : true,
results : {
total: 10,
score: 3,
results: [
{id : 123, name: "test123"},
{id : 123, name: "test4554"}
]
}
};
_.set(myObj, 'results.results', _.uniqBy(_.get(myObj, 'results.results'), 'id'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
My JSON currently looks like this:
{
"_id" : 393,
"item" : 34,
"comments" : [
{
"name" : "kevin",
"messages" : [
"item",
"item"
]
},
{
"name" : "ryan",
"messages" : [
"item",
"item"
]
}
]
}
How could I push new items onto the messages array for the first or second item in the comments array?
db.newcon.update({_id: 393}, { $push: { comments['kevin']: {messages: 39 } } })
Using $elemMatch and $ operator you can update your documents check below query :
db.collectionName.update({"_id":393,"comments":{"$elemMatch":{"name":"kevin"}}},
{"$push":{"comments.$.messages":39}})
Something like this will work:
var newMessage = '39';
comments.forEach(function(item) {
if (item.name === 'kevin') {
item.comments.push(newMessage);
}
});
I create an array of Objects from a database query and call the
array jobListRecords. There are multiple records in the array created that have the same "customerID" and "name".
I would like to create a new array that has one record for each customer with a new field , "jobArray", that contains another array of all of that customers services. (see sortCustomer array down below)
An example of the initial array:
jobListRecords = [
{
"customerID" : "1",
"name" : "Larry Bird",
"serviceID" : "101",
"serviceName" : "Dog Walking"
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"serviceID" : "202",
"serviceName" : "Baby Sitting"
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
Desired Result
sortCustomer Example:
sortCustomer = [
{
"customerID" : "1",
"name" : " Larry Bird",
"jobArray" : [
{
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"jobArray" : [
{
"serviceID" : "202",
"serviceName" : "Baby Sitting"
},
{
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
}
Is their a simple or efficient way of solving this without having to iterate through all the data 3+ times. Thank You for your time, below is one of the several things I tried.
I tried solving this using one example I found but it grouped all the serviceIDs together which is not what I need.
Example that DID NOT work that I tried.
jobListGrouped = _
.chain(jobListRecords)
.groupBy('customerID')
.map(function(value, key) {
return {
CustomerID: key,
services: _.pluck(value, 'serviceID')
}
})
.value();
You're plucking only the serviceIDs into that array. Instead, you would need to do something like
.map(function(values, key) {
return {
customerID: key,
name: values[0].name.
services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
}
})
or even more explicit
.map(function(values, key) {
return _.extend(_.omit(values[0], 'serviceID', 'serviceName'), {
services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
}
})
(where that partial call is the same as function(value) { return _.pick(value, 'serviceID', 'serviceName'); })
Im new to JSON and I have to deal with a complex one.
Please see image below:
It has an error:
I don't know how to properly separate the 2 json arrays. I even tried to use : instead of , on line 18 but I still get errors. BTW, I use http://jsonlint.com/ to validate.
On line 2 you gave a key, but failed to do so on line 19. You have to keep the structure.
Remove the key on line 2, they shouldn't be used for arrays in that way.
Edit: In addition, you are trying to put arrays right in objects, switch the opening and ending object marks ({}) with ([]) for arrays on your first and last line.
[
[
{...},
{...},
...
{...}
],
[
{...},
{...},
...
{...}
],
...
[
{...},
{...},
...
{...}
]
]
I believe the correct way to build this JSON should be:
{
"glEntries": [
{
"generalLedgerId":1,
"accountId": 34,
"amount" : 32334.23,
"descripction": "desc1",
"debit" : "Yes"
},
{
"generalLedgerId":2,
"accountId": 35,
"amount" : 323.23,
"descripction": "desc",
"debit" : "Yes"
},
...
]
}
There are many ways to construct JSON data, but it depends on your data and the way you want to present it. Here are a couple examples - hope it helps:
{
"glEntries": [
{
"object1-prop1": "one"
},
{
"object2-prop1": 1,
"object2-prop2": "two"
},
{
"object3-prop1": [
"a",
"r",
"r",
"a",
"y"
],
"object3-prop1.1": "string"
}
],
"otherEntries": [
{
"objectx": "x"
},
{
"objecty": "y"
},
{
"objectz": [
1,
2,
3,
4
]
}
],
"oneEntry": "json"
}
Other Example:
[
{
"obj1-prop": 222
},
{
"obj2-prop": "object2"
},
{
"obj3-prop": "Object3"
},
[
"a",
"r",
"r",
"a",
"y",
777,
888
],
"string",
178,
{
"objectProp": "testing123"
}
]
You have more {} than needed and will make parsing your JSON more difficult:
Structure will work a lot better like this:
{"glentries":[
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"}
]
}
Now glentries is an array of objects that have multiple properties to them.
alert( glentries[0].property2 )
The parent structure is an Object, so it is expecting a string Key for the second array. It it's supposed to be an array of arrays, you should be using an array and not an Object.