MongoDB Loop: Saving data from variable? - arrays

Working with a frontend variable like below in javascript with many objects... (Note - the scores would be different for each user therefore I would need to be able to get the info from the frontend)
var campgrounds = [{ name: "State Park #1" score: 0, }, { name: "State Park #2" score: 0, }, { name: "State Park #3" score: 0 }]
How would I be able to store that data in MongoDB? Could I somehow loop through the data? Or could I store the entire variable "campgrounds" in Mongo? like $("#quizData").value(campgrounds)
Would I set up a Schema like below? Even if I did I'm not sure how to actually get the data in the variable into Mongo. Not sure how to accomplish my goal. Thanks for any help! :)
var campgroundsSchema = new Schema ({
"campgrounds" : [{
name : {type: String},
score : {type : Number}
}],
});

If you connect to mongo using mongoshell ...
mongo --host localhost:27017
you can issue the following javascript commands...
use campgroundsdb
var campgrounds = [{ name: "State Park #1", score: 0 }, { name: "State Park #2", score: 0, }, { name: "State Park #3", score: 0 }]
db.campgroundscollection.insertMany(campgrounds)
Then find them by issuing...
db.campgroundscollection.find().pretty()
If you want to create a program written in JavaScript it will need the ability to connect to the mongodb process. Node.js tutorials fit this requirement...
https://www.w3schools.com/nodejs/nodejs_mongodb.asp

Related

MongoDB check if key value exists and update only some fields

Let's say I have a MongoDB collection "people" that has the form
[
{
_id: [OBJECT_ID_1],
name: "Paul",
hobby: "rowing",
fixed: 1
},
{
_id: [OBJECT_ID_2],
name: "Selena",
hobby: "drawing",
fixed: 2
},
{
_id: [OBJECT_ID_3],
name: "Emily",
hobby: "jogging",
fixed: 3
}
]
And new data to be inserted of the form
var data = [
{
name: "Paul", // name exists, so keep "fixed" at 1
hobby: "archery",
fixed: 4
},
{
name: "Peter",
hobby: "knitting",
fixed: 5
}
]
I would like to insert/update the collection with the new data. However, if a document with the same "name" already exists, I do not want to update "fixed". The result after inserting the above data should be
[
{
_id: [OBJECT_ID_1],
name: "Paul",
hobby: "archery", // updated
fixed: 1 // not updated, because name existed
},
{
_id: [OBJECT_ID_2],
name: "Selena",
hobby: "drawing",
fixed: 2
},
{
_id: [OBJECT_ID_3],
name: "Emily",
hobby: "jogging",
fixed: 3
},
{ // newly inserted document
_id: [OBJECT_ID_4],
name: "Peter",
hobby: "knitting",
fixed: 5
}
]
The data includes a large number of documents, so I would like to achieve this in one query if possible. What would be the best way to accomplish this? Many thanks!
bulkWrite with updateOne's with $upsert:true seems to work best for you...
bulkWrite not perform a Find operation.
Its (in my case) is necessary to control if it will create a another document.
In my case I just use find check before insert/create method.
if (collection.find({"descr":descr}).limit(1).length === 1) {
//...create method
console.log('Exists')
}

MongoDB Compass GROUP BY value

Lets say that i have the following objects in my mongodb-compass-database:
{
_id: ObjectID("randomString"),
Name: "Test1",
OtherAttribute: 187
},
{
_id: ObjectID("otherRandomString"),
Name: "Test2",
OtherAttribute: 1337
},
{
_id: ObjectID("otherRandomString2"),
Name: "Test1",
OtherAttribute: 23
}
How can I return the "Name"-value if it exist more than one time?
In the example I want to receive "Test1" or the whole object, doesnt matter.
I just need to see if there are any duplicates.
I need to use the MongoDB Compass Find-Input:
Is this possible?

Insert data to Atlas MongoDB error appearing: Insert not permitted while document contains errors

I'm trying to insert data to a collection I created in Atlas MongoDB. The data is following:
[
{ id: 1, performer: 'John Doe', genre: 'Rock', price: 25, day: 1, image: '/img/uploads/1fsd324fsdg.jpg' },
{ id: 2, performer: 'Rebekah Parker', genre: 'R&B', price: 25, day: 1, image: '/img/uploads/2f342s4fsdg.jpg' },
{ id: 3, performer: 'Maybell Haley', genre: 'Pop', price: 40, day: 1, image: '/img/uploads/hdfh42sd213.jpg' }
]
`I get the error : "Insert not permitted while document contains errors."
What am I doing wrong? Please advise.
may be quote problem ...
use double quote to key and property
"id" : 1, "performer : "John Doe" .. ~
This is reslved now, formatting was the problem.
I do the following:
Modify title to "title" and mongo compass works.
Example:
[
{ "id": "1", "performer": "John Doe", "genre": "Rock", "price": "25", "day": "1", "image": "/img/uploads/1fsd324fsdg.jpg" },
]
Reference document: https://docs.mongodb.com/compass/current/documents/insert
It's better that you use MongoDB Compass and connect to it with a connection string:
click on the connection
click on the connection using mongodb compass
then get the compass downloaded from MongoDB according to required OS
but use connection string of connection to MongoDB application
Once you connect to your Compass, you can use import data and then browse your file to use.

MongoDB - Can't push an item to an array inside an object inside an array

I have this object in MongoDB:
{
_id: ObjectId("1"),
data: {
city: "ccp",
universities: [
{
_id: "2"
name: "universityOne"
students: []
},
{
_id: "3"
name: "universityTwo",
students: []
}
]
}
}
I need to push a Student object inside the students array inside the universityOne object inside the universities array, inside the global object.
I tried documentation and come up with this queries.
Mongo shell returns { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }. And nothing changes.
Here are the queries formatted/unformatted, so you can see them:
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[id].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"id._id": ObjectId("2")}]})
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[id].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"id._id": ObjectId("2")}]})
This second query is with the name of the university on the mongo [<identifier>]. But doesn't work either.
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[name].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"name.name": "universityOne"}]})
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[name].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"name.name": "universityOne"}]})
Regards.
UPDATE
Real object:
{
_id: ObjectId("5c6aef9bfc1a2693588827d9"),
datosAcademicos: {
internados: [
{
_id: ObjectId("5c6bfae98857df9f668ff2eb"),
pautas: []
},
{
_id: ObjectId("5c6c140f8857df9f668ff2ec"),
pautas: []
}
]
}
}
I need to add a Pauta to the pautas array. I've set pautas to an array of strings for debugging purpose, so just need to push a "hello world" or whatever string.
I tried this with the answers I've been given:
db.pautas.updateOne({"_id":ObjectId("5c6aef9bfc1a2693588827d9"), "datosAcademicos.internados._id": ObjectId("5c6bfae98857df9f668ff2eb")}, { $push: {"datosAcademicos.internados.$.pautas": "hi"}})
db.pautas.updateOne({"_id":ObjectId("5c6aef9bfc1a2693588827d9"), "datosAcademicos.internados._id": ObjectId("5c6bfae98857df9f668ff2eb")}, { $push: {"datosAcademicos.internados.$.pautas": "hi"}})
Update 2:
Mongo version: v4.0.2
Using Robo 3T.
I created a test database
And tried this command
Still not working.
There are 3 issues with your statement. First, the root ID field is "id" and you're querying the "_ID".
Second, you should put the match fields altogether. This update works as expected.
Third, you should use "$" to select the nested array position, not "$[id]".
db.pautas.updateOne(
{ "id": ObjectId("1"), "data.universities._id": "2"},
{$push:
{"data.universities.$.students": {name: "aStudentName", age: 22}}
})
Answer to the question UPDATE:
The update statement worked just fine.
Update statement
Record after update - I ran my update with your data and then the update code you posted, both worked just fine.

Ignoring a field mongodb request

Let's say we have objects like this in a mongodb collection:
{
_id: 00000001
colors: ["green", "yellow"],
houses: [
{
number: 1,
owner: "John"
},
{
number: 2,
owner: "John"
},
{
number:3,
owner: "Dave"
}
]
},
{
_id: 00000002
colors: ["green", "red"],
houses: [
{
number: 15,
owner: "Dave"
},
]
}
So, to get every object where the color array contains the color green the query I would need to write would look smth like this: collection.find({colors: "green"});
Now if I would like to get all the objects in which John owns a house, how would I formulate such a query?
Basically what I am asking is, if my query would be collection.find({houses: {owner: "John", number: ?}}) what would I need to replace the "?" with to tell mongo that I don't care what value number has.
Or maybe there is another approach that I haven't thought of?
Thank you for any help!
(Btw this is a made up example hence why the IDs look weird and the object in itself doesn't seem very useful.)
To query an array of objects you can use the dot notation, try:
db.collection.find({ "houses.owner": "John"}})

Resources