How do i get my data?!

PROBLEM: Cant figure out the syntax to get out specific data from my documents
GOAL: I want to have access to my collection and use dot notation to get in to an document and get its information.

I have a database that looks like this:
DatabaseName
Collection1
Collection2
Collection3

In every Collection do i have multiply objects and in that i have data about the object.

I have tried to extract data for my database in over 10 hours and haven´t find the solution. I may have forgotten something from the introduction course or have understand. That is why that i would appriciate som visuals with your answers, code examples and so on. Down below can you see my database and code in VS.

MongoDB
:file_cabinet: ClashOfClans (database)
:file_folder: darkelexirTroop (collection)
:file_folder: elexirTroop (collection)
:file_folder: superTroops (collection)

Inside darkElexirTroop

minion:
  image:"none"
  name: "Minion"
  preferredTarget: "Everything"
  attackType: "Ranged"
  housingSpace: 2
  movementSpeed: 32
  attackSpeed:
    value: 1
    unit: "s"
  darkBarracklvlReq: 5
  attackRange:
    range: 2.75
    value: "tiles"
  superTroop: true
  superTroopReqLvl: 8
  levels: (contain a document per level with info like above)
    levelOne:
    levelTwo
//it keeps going

:camera_flash: img is attached.

My code in VS:
I have two files that has to do with mongoDB. I have followed the node.js guide. I have installed Express, what i know do this not provide any problems or change the way to get the data from the documents?!

FileOne: index.js
Code:

const express = require("express");
const { MongoClient } = require("mongodb");
const uri = require("./db/connection.js");
const app = express();
// const port = 3001;
// const routes = require("./Routes");
// app.use("/", routes);

console.log("connectDB:", uri);
const client = new MongoClient(uri);
const dbName = "ClashOfClans";
const collName = "elexirTroop";
const wholeColl = client.db(dbName).collection(collName);

const connectDB = async () => {
  try {
    await client.connect();
    console.log("Connected: ", dbName);
  } catch (err) {
    console.error(`Error connecting: ${err}`);
  }
};
const documentToFind = { elexirTroop: "barbarian" };

const main = async () => {
  try {
    await connectDB();
    let result = await wholeColl.findOne(documentToFind);
    console.log(result);
  } catch (err) {
    console.error(`Error DID COME UPP:${err}`);
  }
};
main();

app.listen(3000, async () => {
  await connectDB();
  console.log("App is running");
});

module.exports = app;

File two: connection.js

module.exports = uri =
  "mongodb+srv://oscarThroedsson:passwordHidden@cluster0.5xvzvb7.mongodb.net/?retryWrites=true&w=majority";

Explanation to the code:

  1. I use my connection string in connection.js en export it.
  2. Req it in index.js on line 3
  3. I declare to varible
  • dbName: with the database name.
  • collName: with the Collection name.
  1. I declare the connection for the database and collection in wholeColl
const wholeColl = client.db(dbName).collection(collName);

This part is just russion roulette.

const connectDB = async () => {
  try {
    await client.connect();
    console.log("Connected: ", dbName);
  } catch (err) {
    console.error(`Error connecting: ${err}`);
  }
};
const documentToFind = { elexirTroop: "barbarian" };

const main = async () => {
  try {
    await connectDB();
    let result = await wholeColl.findOne(documentToFind);
    console.log(result);
  } catch (err) {
    console.error(`Error DID COME UPP:${err}`);
  }
};
main();

I have also connected the message i get in terminal but the msg is below:

 ~/Documents/MyOwnProjects/clashOfClanStats/server   main  node index.js
connectDB: mongodb+srv://oscarThroedsson:passwordHidden@cluster0.5xvzvb7.mongodb.net/?retryWrites=true&w=majority
Connected:  ClashOfClans
Connected:  ClashOfClans
App is running
null

I dont know what more information that you would want to be able to help me. If can provide any code, please do. But also any docs would be appreciated.

Hello, @Oscar_Throedsson ! Welcome to the MongoDB community! :wave:

I tried your code and it should work fine, if you specify proper conditions in the .findOne() method.

Try to change your query to something like this:

let result = await wholeColl.findOne({});
console.log(result);

OR

let result = await wholeColl.findOne({
  'minion.name': 'Minion'
});
console.log(result);

I would suggest you to read more about CRUD operations using MongoDB Node.js driver. You can start with reading every chapter about read operations and write operations.

1 Like

Hey Slava!

Thank you for your response.

I figure it out and this is the code i came up with.

const express = require("express");
const { MongoClient } = require("mongodb");
const uri = require("./db/connection.js");
const app = express();
// const port = 3001;
// const routes = require("./Routes");
// app.use("/", routes);

console.log("connectDB:", uri);
const client = new MongoClient(uri);
const dbName = "ClashOfClans";
const collName = "elexirTroop";
const wholeColl = client.db(dbName).collection(collName);

const connectDB = async () => {
  try {
    await client.connect();
    console.log("Connected: ", dbName);
  } catch (err) {
    console.error(`Error connecting: ${err}`);
  }
};
const documentToFind = { barbarian: { name: "barbarian" } };

const main = async () => {
  try {
    await connectDB();
    let result = await wholeColl.find({}).toArray(); // Take out the whole doc
    let barbarianData = result[0].barbarian; // looking at the first place
    console.log("barbarianData", barbarianData);
    console.log("modify: ", barbarianData.name);

    // console.log("result", result);
  } catch (err) {
    console.error(`Error DID COME UPP:${err}`);
  }
};
main();

app.listen(3000, async () => {
  await connectDB();
  console.log("App is running");
});

module.exports = app;

What I am trying to do is:
I want to find a collection with a certain name. Then go to a doc with a certain name. Then I want all the keys and values to be declared/returned in to a variable so i just can access the data by writing

varible.key

I would like it to be this easy.

const dbName = "ClashOfClans";
const collName = "elexirTroop";
const dataDoc = client.db(dbName).collection(collName); //Want to catch the doc data here. 

console.log(dataDoc.name) 

I just want the data from a doc to be saved in the varible. Think of handling object from a API…

in this row am i Thinking the following

const dataDoc = client.db(dbName).collection(collName); //Want to catch the doc data here. 

I am fetching the data from the database ClashOfClans (client.db(dbName) ang wan the following data in this document returned (.collection(collName);

This would also make it easier to fetch nested docs.

console.log(´Your firstname is ${dataDoc.name.firstName} and your lastname is ${dataDoc.name.lastName}`)

Maybe we can make it work like that but i

I tried this:

const client = new MongoClient(uri);
const dbName = "ClashOfClans";
const collName = "elexirTroop";
const wholeColl = client.db(dbName).collection(collName);
const retriveTroopDoc = { name: "barbarian" };

Then in the method I tried this:

const main = async () => {
  try {
    await connectDB();
    // let result = await wholeColl.find(documentToFind).toArray();
    // troop = result[0].barbarian;
    troop = await wholeColl.findOne(retriveTroopDoc);

    console.log("retriveTroopDoc", retriveTroopDoc);
    console.log("troopData: ", troop);

    // console.log("result", result);
  } catch (err) {
    console.error(`Error DID COME UPP:${err}`);
  }
};
main();

It is really important I get an object… The front-end will be third world war for my head to code if i have an array.

My database look like this:

ClashOfClans - (database)

darkElexirTroop (collection)

_id:“randome id”
minion: (object/document)
hogRider: (object/document)
valkyrie: (object/document)
golem: (object/document)
witch: (object/document)
lavaHound: (object/document)
bowler: (object/document)
iceGolem: (object/document)
headhunter: (object/document)
apprenticeWarden: (object/document)

elexirTroop (collection)

_id:“randome id”
barbarian: (object/document)
archer: (object/document)
giant: (object/document)
goblin: (object/document)
wallBreaker: (object/document)
balloon: (object/document)
wizard: (object/document)
healer: (object/document)
dragon: (object/document)
pekka: (object/document)
babyDragon: (object/document)
miner: (object/document)
electroDragon: (object/document)
yeti: (object/document)
dragonRider: (object/document)
electroTitan: (object/document)

I have read everything you linked, but I dont find it helpfule. I dont understand what I am doing wrong. Everything i read it looks like I am doing the right thing to get the data.

You are querying a field called name for the value barbarian as in

While the little amount of data you shared does not even have a field called name.

I strongly recommend that you take a look at

1 Like

Hey Steve.
Everything is on 3000 lines, so i didnt share everything. But here you go.

Here can you see the barbarian doc with the name of Barbarian.

I want all the data in barbarian be returned as an object so i can do dot notation in VS.

so your query must be

{ "barbarian.name" : "Barbarian" }
1 Like

I have tried that as well. I have done the courses, I have read the documentation, i have watched a lot of youtube videos. I have asked in the discord. I don´t understand what I´am doing wrong!
file: index.js

const express = require("express");
const { MongoClient } = require("mongodb");
const uri = require("./db/connection.js");
const app = express();
// const port = 3001;
// const routes = require("./Routes");
// app.use("/", routes);

console.log("connectDB:", uri);
const client = new MongoClient(uri);
const dbName = "ClashOfClans";
const collName = "elexirTroop";
const wholeColl = client.db(dbName).collection(collName);
const retriveTroopDoc = { barbarian: { name: "Barbarian" } };//here i tried your suggestion

const connectDB = async () => {
  try {
    await client.connect();
    console.log("Connected: ", dbName);
  } catch (err) {
    console.error(`Error connecting: ${err}`);
  }
};
// const documentToFind = { barbarian: { name: "barbarian" } }; / i had tried it before

const main = async () => {
  try {
    await connectDB();
    // let result = await wholeColl.find(documentToFind).toArray();
    // troop = result[0].barbarian;

    troop = await wholeColl.findOne(retriveTroopDoc);
    console.log("URI: ", uri);
    console.log("troop: ", troop);

    // console.log("result", result);
    // console.log("troop: ", troop.name);
  } catch (err) {
    console.error(`Error DID COME UPP:${err}`);
  }
};
main();

app.listen(3000, async () => {
  await connectDB();
  console.log("App is running");
});

module.exports = app;

Not to get confused. Code that is commented out is code i have tried before and have giving me null or undefined.

The code above game me null.

connectDB: mongodb+srv://oscarThroedsson:password@cluster0.5xvzvb7.mongodb.net/?retryWrites=true&w=majority
Connected: ClashOfClans
Connected: ClashOfClans
App is running
URI: mongodb+srv://oscarThroedsson:StJrtPy0eoXOCCNb@cluster0.5xvzvb7.mongodb.net/?retryWrites=true&w=majority
troop: null ← Here is console.log("troop: ", troop.name);

This is how i have set up my VS fil.

Folders:
db… contain js file: “connection.js”

module.exports = uri =
  "mongodb+srv://oscarThroedsson:StJrtPy0eoXOCCNb@cluster0.5xvzvb7.mongodb.net/?retryWrites=true&w=majority";

This string is console.log above client and in method main.

index.js- All the code is above

I really don´t know what to show you or what information to give you. As my understanding, null means it cant find what I am searching for.

the above is not my suggestion. my suggestion is

Oh, thanks!!

if I

console.log(troop);

I get all the documents inside the collection elexirtroop with this code.
And if i do

console.log(troop.barbarian);

I get the document barbarian.

If i want a value i need to do.

console.log(troop.barbarian.name);

Which will give me the value on the key “name”.

I thought that find returned a document not a whole collection, or have I misunderstand how it works!?

If you look at my mongoDB database:
ClashOfClans is the Database.
elexirTroop is the Collection
Barbarian is a Document

I interpret that the troop variable returns a collection that contains the key value barbarian, and not the document.

If you want, can you please help me clarify it, if I have misunderstood something.

Thank you so much for your help.

You seem to be confused between what is a document in a collection and what is an object in a document.

If you look at your own screenshots you will see that your elexirTroop collection as 1 document. It is indicated

QUERY RESULTS:1-1 OF 1

Just beside the field barbarian you will see that it is an Object within the single document, the single _id shown. As such, the fields archer, giant, goblin, … all refer to Object within the same unique document from your collection.

Hey Steve.

Have tried to read a littlebit before I answer you.

I interperate your text that a collection is a document? But that must be wrong, becuase a collection contains document, right?.

I thought all of the data inside elexirtroops was one document, but when i have read more i would say the following.

Everything between the curlybrackets is a single document. So every troop is a document in elexirTroops.

elexirtroops: Collection
-barbarian: Document
-archer: Document

Inside every Document, we have fields av values. What i learned is key: value. But that doesn´t matter right now. Correct?

Does that mean i should have curlybrackets {} efter barbarian: and in the end to separate the document to its fields and values?

This interpretation is wrong. A collection contains one or more documents. Your elexirTroop contains only one document and its _id is ObjectId( “64e…d22” ).

The fields barbarian and archer within the only document of your elixirTroop are Object. If you look closely beside barbarian you will see a colon and the word Object.

Yes if you want barbarian be a separate document from archer.

I got it!

I understand the structure now. I sorted it out!

Thank for your patience and advises!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.