limit records in mongodb query [duplicate] - javascript

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 7 years ago.
This is my document in MongoDB and I need to limit the output:
{
"_id": ObjectId("55880fb8c3addd201ee2f70e"),
"title": "Sales",
"level1": [{
"name": "Master",
"link": "/sales/master"
}, {
"name": "eCommerce",
"link": "/sales/ecommerce"
}]
}
My search query is:
db.collection.find({
title: "Sales",
"level1.name": "Master"
}, {
"title": 1,
"level1.name": 1,
"level1.name": "Master"
})
This is the expected output:
{
"_id": ObjectId("55880fb8c3addd201ee2f70e"),
"title": "Sales",
"level1": [{
"name": "Master",
"link": "/sales/master"
}]
}

You can use aggregation by $unwind level1 array to get expected result like following:
db.collection.aggregate({$unwind:"$level1"},{$match:{"level1.name":"Master","title" :"Sales"}})
If you want all under one array you can group it like :
db.collection.aggregate({$unwind:"$level1"},{$match:{"title" :"Sales","level1.name":"Master"}},{$group:{_id:"_id","title":{$first:"$title"},"level1":{$push:"$level1"}}})

Please try the below query :
db.collection.find({title :"Sales",
level1: {$elematch: {name" : "Master"}}},
{title : 1, level1.$ : 1});

Related

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.

see undefined when try to parse json [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I have tried to parse this JSON file. But I see undefined.
I need to receive only value, where the key equals level1.
[{
"id": 2,
"name": "Peter",
"products": [{
"title": "first",
"price": 100
},
{
"title": "second",
"price": 200,
"desciption": [{
"level1": "good",
"level2": "bad"
},
{
"level3": "super",
"level4": "hell"
}
]
}
],
"country": "USA"
}]
const fs = require('fs');
let file = fs.readFileSync("./file.json");
let parsed = JSON.parse(file);
console.log(parsed["name"])
console.log(parsed.name);
and I see in the conlose "undefined"
Your JSON data represents an array of objects. If after parsing you want the property "name" of the first element, it's:
console.log(parsed[0]["name"])
or
console.log(parsed[0].name);

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Mongo Aggregation

I have following documents in my collection
{
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample1",
"slug": "samplenews",
"cat": "sports",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-10-23T14:06:57.0Z"),
} {
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample2",
"slug": "samplenews2",
"category": "entertaintment",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-10-22T14:06:57.0Z"),
} {
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample3",
"slug": "samplenews3",
"category": "entertaintment",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-9-22T14:06:57.0Z"),
} {
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample4",
"slug": "samplenews4",
"category": "other",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-10-22T14:06:57.0Z"),
}
I need one query to get top 5 latest news from each category.any suggestions?
Assuming you have the latest version of mongodb installed, one way of doing it is:
Sort the records based on the published_date in descending order.
group the records based on their category. For each group, collect all the records together in an array.
In the javascript/client side code, slice the top 5 records, of each group(category).
The $slice is not available in the server side $project aggregation pipeline operator, which holds us from performing the operation on the server side.
var result = db.collection.aggregate(
[
{$sort:{"published_date":-1}},
{$group:{"_id":"$category","values":{$push:"$$ROOT"}}}
]
).map(function(doc){
return {"category":doc._id,"records":doc.values.slice(0,5)};
});
The result variable will now be an array of documents. Each document representing each category and in turn having an array of top 5 records.
You can sort and then limit your request.
$top_five_other = iterator_to_array($db->find(array('category'=>'other')->sort(array('published_date'=>-1))->limit(5));
you can try aggregate query
1-db.collection.aggregate({ $group : { _id : { category:"$category"}, total : { $sum : 1 }}},{$sort:{_id:1}})
OR
db.collection.aggregate({ $group : { _id : { category:"$category"}, total : { $sum : 1 }}},{$sort:{_id:1}})..forEach( function(myDoc) {
print(myDoc._id.category);
})

Object.keys() Get Number Of Child Items [duplicate]

This question already has an answer here:
Get length of a JavaScript array [duplicate]
(1 answer)
Closed 8 years ago.
I have the following data source -- converted to JSON using to XML using X2JS:
{
"blog": {
"article": [
{
"id": "1",
"author": "eat-sleep-code",
"title": {
"__cdata": "Thefirstarticle."
},
"content": {
"__cdata": "\nThisismyfirstarticleinmytestsite.\n"
},
"createdate": "2014-05-09"
},
{
"id": "2",
"author": "eat-sleep-code",
"title": {
"__cdata": "Thesecondarticle."
},
"content": {
"__cdata": "\nThisismysecondarticleinmytestsite.Thisarticle'screatedateisactuallyearlier.\n"
},
"createdate": "2014-05-08"
}
]
}
}
I am trying to find the number of "articles".
Object.keys(jsonObject).length; just gets me 1. I am guessing because it is finding one "blog" item.
jsonObject.blog.article.length

Categories