MongoDB - How to retrieve only one specific document from a collection - database

I have created a database called "Cars" and a collection inside it as, "Cars_info". I have inserted 8 documents inside it as follows.
db.Cars_info.insertMany([
{ car_id: "c1", Company: "Toyota", Model: "Aqua", Year: 2020, Price_in_usd: 25000, Category: "High-end", Country: "Japan" },
{ car_id: "c2", Company: "Toyota", Model: "Premio", Year: 2019, Price_in_usd: 35000, Category: "High-end", Country: "Japan" },
{ car_id: "c3", Company: "Audi", Model: "A6", Year: 2020, Price_in_usd: 55000, Category: "High-end", Country: "Germany" },
{ car_id: "c4", Company: "Tata", Model: "Nano", Year: 2015, Price_in_usd: 10000, Category: "Low-end", Country: "India" },
{ car_id: "c5", Company: "Volkswagen", Model: "Taos", Year: 2022, Price_in_usd: 35000, Category: "High-end", Country: "Germany" },
{ car_id: "c6", Company: "Ford", Model: "Figo", Year: 2019, Price_in_usd: 26000, Category: "High-end", Country: "America" },
{ car_id: "c7", Company: "Mahindra", Model: "Thar", Year: 2018, Price_in_usd: 18000, Category: "Low-end", Country: "India" },
{ car_id: "c8", Company: "Honda", Model: "Vezel", Year: 2015, Price_in_usd: 33000, Category: "High-end", Country: "Japan" }
])
Here I want to retrieve only the third document from the collection. But without matching any field value. like,
db.Cars_info.find({"car_id":"c3"}).pretty()
Is there any way to do this?

You need .skip() and .limit().
Take the document by starting index: 2 and with only 1 document, which is the third document.
Update: Thanks and credit to #Wernfried for pointing out, you need .sort() to guarantee to get the nth of the document. For your scenario, you have to sort by car_id.
Sort Consistency
MongoDB does not store documents in a collection in a particular order. When sorting on a field that contains duplicate values, documents containing those values may be returned in any order.
db.Cars_info.find()
.sort({ "car_id": 1 })
.skip(2)
.limit(1)

Related

MongoDB - Update an object from a nested array

{ _id: 1, first : "Maria",
travel : [
{ country: "Canada", visits: 3, rating: 7 },
{ country: "Poland", visits: 1, rating: 8 },
{ country: "Thailand", visits: 2, rating: 9 } ] },
{ _id: 2, first : "Chen",
travel : [
{ country: "Thailand", visits: 3, rating: 7 },
{ country: "Canada", visits: 2, rating: 9 },
{ country: "Costa Rica", visits: 4, rating: 8 } ] },
{ _id: 3, first : "Gladys",
travel : [
{ country: "Canada", visits: 1, rating: 8 },
{ country: "Thailand", visits: 2, rating: 9 },
{ country: "Australia", visits: 3, rating: 10 } ]}
])
I need to update the visits Maria made to Canada to 5, so I have to use some sort of "double filter" (?) But I'm not sure how to do that
Okay, I got how to make that "double filter" : Array filters and $[identifier]
Here
db.viajeros.updateOne( { first: "Maria"},
{ $set: {"travel.$[elem].visits": 5}},
{ arrayFilters: [{"elem.country": "Canada"}]} )

Using React to create table from data

as the question suggests I am brand new to react and am trying to create a table to display some data.
Here's what I have so far
const { Component } = React;
const { render } = ReactDOM;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
"manufacturer": "Toyota",
"model": "Rav4",
"year": 2008,
"stock": 3,
"price": 8500
},
{
"manufacturer": "Toyota",
"model": "Camry",
"year": 2009,
"stock": 2,
"price": 6500
},
{
"manufacturer": "Toyota",
"model": "Tacoma",
"year": 2016,
"stock": 1,
"price": 22000
},
{
"manufacturer": "BMW",
"model": "i3",
"year": 2012,
"stock": 5,
"price": 12000
},
{
"manufacturer": "Chevy",
"model": "Malibu",
"year": 2015,
"stock": 2,
"price": 10000
},
{
"manufacturer": "Honda",
"model": "Accord",
"year": 2013,
"stock": 1,
"price": 9000
},
{
"manufacturer": "Hyundai",
"model": "Elantra",
"year": 2013,
"stock": 2,
"price": 7000
},
{
"manufacturer": "Chevy",
"model": "Cruze",
"year": 2012,
"stock": 2,
"price": 5500
},
{
"manufacturer": "Dodge",
"model": "Charger",
"year": 2013,
"stock": 2,
"price": 16000
},
{
"manufacturer": "Ford",
"model": "Mustang",
"year": 2009,
"stock": 1,
"price": 8000
},]
};
}
render() {
const columns = [{
Header: 'Manufacturer',
accessor: 'manufacturer'
},{
Header: 'Model',
accessor: 'model'
},{
Header: 'Year',
accessor: 'year'
},{
Header: 'Stock',
accessor: 'stock'
},{
Header: 'Price',
accessor: 'price'
},{
Header: 'Option',
accessor: 'option'
}]
return (
<div>
<Table
data = {this.state.cars}
colums = {columns}
/>
</div>
);
};
}
ReactDOM.render(<App />, document.getElementById("app"))
Im getting errors that the table is not defined but when I try to define it, that throws me errors as well. The table doesn't need to be fancy, the simpler the better in fact.
I was thinking of doing something like what was done in this post: https://codereview.stackexchange.com/questions/212250/generating-a-table-based-on-an-array-of-objects.
Any suggestions?
UPDATE
After the very helpful comment from Crispen Gari, I made some tweaks and came up with this
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
manufacturer: "Toyota",
model: "Rav4",
year: 2008,
stock: 3,
price: 8500,
},
{
manufacturer: "Toyota",
model: "Camry",
year: 2009,
stock: 2,
price: 6500,
},
{
manufacturer: "Toyota",
model: "Tacoma",
year: 2016,
stock: 1,
price: 22000,
},
{
manufacturer: "BMW",
model: "i3",
year: 2012,
stock: 5,
price: 12000,
},
{
manufacturer: "Chevy",
model: "Malibu",
year: 2015,
stock: 2,
price: 10000,
},
{
manufacturer: "Honda",
model: "Accord",
year: 2013,
stock: 1,
price: 9000,
},
{
manufacturer: "Hyundai",
model: "Elantra",
year: 2013,
stock: 2,
price: 7000,
},
{
manufacturer: "Chevy",
model: "Cruze",
year: 2012,
stock: 2,
price: 5500,
},
{
manufacturer: "Dodge",
model: "Charger",
year: 2013,
stock: 2,
price: 16000,
},
{
manufacturer: "Ford",
model: "Mustang",
year: 2009,
stock: 1,
price: 8000,
},
],
};
}
render() {
return (
<div>
<Table data={this.state.cars} />
</div>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props.data[0]);
return (
<table border="1">
<thead>
{tableHeads.map((tableHead, i) => (
<th key={i}>{tableHead}</th>
))}
</thead>
<tbody>
{this.props.data.map((value, key) => (
<tr key={key}>
<td>{value.manufacturer}</td>
<td>{value.model}</td>
<td>{value.year}</td>
<td>{value.stock}</td>
<td>{value.price}</td>
</tr>
))}
</tbody>
</table>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"))
This post can be considered closed
Hey, Try this code if you face any problems of understanding, let me know. I recommend you to copy and paste this code if it works go through it and try to understand. The most important thing is to understand JavaScript higher order function map
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
manufacturer: "Toyota",
model: "Rav4",
year: 2008,
stock: 3,
price: 8500,
},
{
manufacturer: "Toyota",
model: "Camry",
year: 2009,
stock: 2,
price: 6500,
},
{
manufacturer: "Toyota",
model: "Tacoma",
year: 2016,
stock: 1,
price: 22000,
},
{
manufacturer: "BMW",
model: "i3",
year: 2012,
stock: 5,
price: 12000,
},
{
manufacturer: "Chevy",
model: "Malibu",
year: 2015,
stock: 2,
price: 10000,
},
{
manufacturer: "Honda",
model: "Accord",
year: 2013,
stock: 1,
price: 9000,
},
{
manufacturer: "Hyundai",
model: "Elantra",
year: 2013,
stock: 2,
price: 7000,
},
{
manufacturer: "Chevy",
model: "Cruze",
year: 2012,
stock: 2,
price: 5500,
},
{
manufacturer: "Dodge",
model: "Charger",
year: 2013,
stock: 2,
price: 16000,
},
{
manufacturer: "Ford",
model: "Mustang",
year: 2009,
stock: 1,
price: 8000,
},
],
};
}
render() {
return (
<div>
<Table data={this.state.cars} />
</div>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
const tableHeads = Object.keys(this.props?.data[0]);
return (
<table border="1">
<thead>
{tableHeads.map((tableHead, i) => (
<th key={i}>{tableHead}</th>
))}
</thead>
<tbody>
{this.props?.data?.map((value, key) => (
<tr key={key}>
<td>{value?.manufacturer}</td>
<td>{value?.model}</td>
<td>{value?.year}</td>
<td>{value?.stock}</td>
<td>{value?.price}</td>
</tr>
))}
</tbody>
</table>
);
}
}
export default App;
I Hope this will help you, Good Luck

ReactJS: Group data by months in the same year

I have data from api that looks like the following
[{
commission_total: "4740.00"
country: "Kentop"
created_at: "Jun 30, 2020"
deposit: "0.00"
}
{
commission_total: "4760.00"
country: "Kentop2"
created_at: "Jul 1, 2020"
deposit: "0.00"
}]
I am trying to group the data by month of the same year. How do i go about this? I am open to lodash, moment etc. Kindly assist
Try with teh following:-
let data= [{
commission_total: "4740.00"
country: "Kentop"
created_at: "Jun 30, 2020"
deposit: "0.00"
},
{
commission_total: "4760.00"
country: "Kentop2"
created_at: "Jul 1, 2020"
deposit: "0.00"
}]
var grouped = _.mapValues(_.groupBy(data, 'created_at'),
datalist => datalist.map(item => _.omit(item, 'created_at')));
console.log(grouped);

Getting objects in an array that has a specific property

Alright, so I am trying to make an ArtistPage, and I need to put all the albums by that artist, on the page. I put a property called artistName in each album as a way of kinda referencing it but idk if that is the correct practice.
This is the results of a variable called getAlbums that i have in the code that returns an array of objects, which are all the albums in the 'database' -->
[
{name: "The Cool", genre: "Hip-Hop", artistName: "Lupe Fiasco", year: "2006", isExplicit: "true", …}
{name: "Food & Liquor", artistName: "Lupe Fiasco", genre: "Hip-Hop", year: "2006", isExplicit: "true", …}
{name: "Flume", artistName: "Flume", genre: "Electronic", year: "2012", isExplicit: "true", …}
{name: "Skin", artistName: "Flume", isExplicit: "true", genre: "Electronic", year: "2016", …}
{name: "Hybrid Theory", artistName: "Linkin Park", isExplicit: "true", genre: "Nu-Metal", year: "2000", …}
{name: "Views", artistName: "Drake", genre: "Hip-Hop", year: "2016", isExplicit: "true", …}
{name: "2014 Forest Hills Drive", artistName: "J.Cole", isExplicit: "true", genre: "Hip-Hop", year: "2014", …}
{name: "Marshal Matthers LP", artistName: "Eminem", isExplicit: "true", genre: "Hip-Hop", year: "2000", …}
]
I'm using a function to try and loop though all the properties but its wrong ahh.
It only returns one album
getAlbumsByArtist(artistName: any) {
for (var i = 0; i <= this.getAlbums.length - 1; i++) {
if (this.getAlbums[i].artistName === this.artistName) {
return this.getAlbums[i];
}
}
}
So if I wanted to retrieve ALL objects that has the property "artistName: Flume" in this array, how would I go about doing that?
You can use Array.prototype.filter():
getAlbumsByArtist (artistName: any) {
return this.getAlbums.filter(album => album.artistName === artistName);
}
You could even define a generic method to search by any property like this:
getAlbumsByProperty (property: string, value: any) {
return this.getAlbums.filter(album => album[property] === value);
}
and call that like database.getAlbumsByProperty('artistName', 'Flume')
You can use HigherOrder functions in this case.
var albums=array.filter(album=> {
if(album.artistName==='Flume') {
return album;
}
})
console.log("ans", albums);
Working Fiddle:
https://jsfiddle.net/241wkzph/

What schema structure to use for this app?

I want to create an expense tracking app but don't know how to make my schema structure.
The layout:
The schema:
module.exports = {
expenseList: [
{
uid: 'some-uid1',
createdAt: 'some-date1',
expenseItems: [
{
date: 'date11',
desc: 'desc11',
amount: 'amount11'
},
{
date: 'date11',
desc: 'desc11',
amount: 'amount11'
}]
},
{
uid: 'some-uid',
createdAt: 'some-date',
expenseItems: [
{
date: 'date1',
desc: 'desc1',
amount: 'amount1'
},
{
date: 'date1',
desc: 'desc1',
amount: 'amount1'
},
{
date: 'date1',
desc: 'desc1',
amount: 'amount1'
}]
}
]
};
How do I change my schema so I can loop through expenses and display createdAt property as a clickable link that redirects to that expense items?
When do I use Arrays and when do I use Objects in my schema?
Where do I need uid (unique ids)?
I will use firebase for this app
You have an expenseList with a date and expenseItems associated with it. You can have a schema roughly like this. expenseList will be an array of objects. Each expenseList is an object containing uid (to uniquely identify the list), createdAt and array of expenseItems with its own set of properties.
expenseList: [{
uid: 'some-uid',
createdAt: 'some-date',
expenseItems: [
{
date: 'date1',
desc: 'desc1',
amount: 'amount1'
},
{
date: 'date1',
desc: 'desc1',
amount: 'amount1'
}
]
}]
You can iterate over this expenseList to display createdAt in your first screen. On clicking of that, depending on the unique id of that expenseList, fetch the expenseList and display the expenseItems on the second screen.
I have not used firebase before, so you might have to tweak the schema a little.

Resources