Adding a movie to a user's list of favourites in MongoDB - arrays

I'm currently learning full-stack development and I'm having trouble on a task where I have to insert a movie ID into a users list of favourites using Mongodb.
The user I've created is:
{ "_id" : ObjectId("5e1501c6abeeaf482847d46e"),
"UserName": "JulijaDa",
"Password": "FwPreviledges",
"Email": "Julija.Da#live.ru",
"Birhday": {
"$date": "1995-03-16T00:00:00.000Z"
},
"Favs":[
{
"ObjectId": "5e1352793e9e6a804448db0c"
}
]
}
This user currently has only one favourite movie (5e1352793e9e6a804448db0c) and I need to add another (5e1352793e9e6a804448db0e) but, using this method:
db.user.update({
"UserName": "JulijaDa"
}, {
$push: {
"Favs": ObjectId("5e1352793e9e6a804448db0e")
}
})
Mongo returns:
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
I'm following the instructions but, honestly, I'm starting to pull my hair out over here. Can someone tell me what I'm doing wrong? I can also provide more information if needed but, this is basically all I have right now!
Thank you in advance

Through a lot of trial and error, it seems the required code to add a favourite to his user in the database is:
db.[collection name].update(
{ _id: ObjectId("[ID of item being updated]") },
{ $push: { [Name of key]: { [value being added] } } }
)
In the above example, it would look like this:
db.users.update(
{ _id: ObjectId("5e1501c6abeeaf482847d46e") },
{ $push: { Favs: { ObjectId: "5e1352793e9e6a804448db0e" } } }
)
This will added the correct value to the correct fields.
I hope this helps other who are struggling too.

Related

Is there a mongoDB runCommand that returns multiple collections?

I'm trying to write a mongoDB runCommand that returns multiple collections with one command.
I have successfully used the find command within runCommand but I'm unsure how to return multiple find searches. It's important that they are not merged.
Something similar to:
db.runCommand(
[{
"find": "venues"
},
{
"find": "guests"
}]
)
Ideally the result would follow something similar to this structure:
{
"venues": {all venue data from mongo},
"guests": {all guest data from mongo}
}
As I see, this question has nothing common with runCommand.RunCommand just runs a single command. What you really need is to use unionWith aggregate stage and possibly some post data processing.
db.orders.aggregate([
{
$unionWith: {
coll: "inventory",
pipeline: [
{
$addFields: {
"fromInventory": 1 // add a flag that shows that this data is not from original collection
}
}
]
}
},
{
"$group": {
"_id": "$fromInventory",
"content": {
"$addToSet": "$$ROOT"
}
}
},
{
"$project": {
"content": 1, // also it's possible to exclude a flag from output via: `"content.fromInventory": 0,` instead `"content" : 1`
_id: 0
}
}
])
See here. You may need to improve this result further for example with $replaceRoot

Query Object Array inside another Object Array

I need to get the value "no_tilt" but I just cannot figure it out, I was trying something like this..
collectionName.find({
"Shape.layers.vector_tagging": {
$elemMatch: { "1.shapes": { $elemMatch: {0: "Label"} } }}
})
Ok so I downloaded Robot 3T and started testing, and I was finally able to do it, here it is in case anyone finds it useful
db.getCollection('myCollection').find({
"Shape.layers.vector_tagging": {
$elemMatch: { "shapes": { $elemMatch: {"tags.Label":"no_tilt"} } }}
})

When using db.someDb.update([]), how do you $set an array in Mongodb without creating an object?

I've seen similar questions to update and set, but none seem to tackle what I'm talking about. Let's say you have antsDb with the below docs
{ "name": "ant1", "antId": 1, "colId": "colony1" }
{ "name": "ant2", "antId": 2, "colId": "colony1" }
{ "name": "ant3", "antId": 3, "colId": "colony2" }
and you have colonyDb with
{ "colId": "colony1", "jobsArray": ["findFood", "workHard", "carryFood", "feedQueen"] }
{ "colId": "colony2", "jobsArray": ["childCare", "cutLeaves", "feedQueen"] }
I want to update every ant so that they have the jobsArray for their respective colony. But I don't want to create an object when I set the jobsArray for the ants. I thought I could just put
db.colonyDb.aggregate([]).forEach(function(col) {
db.antsDb.update([
{
"colId": col.colId
},
{
$set: {
"myAntJobs": col.jobsArray
}
}
])
})
and that would set an array called myAntJobs on each matching ant document where it doesn't exist, resulting in
{ "name": "ant1", "antId": 1, "colId": "colony1", "myAntJobs": ["findFood", "workHard", "carryFood", "feedQueen"] }
{ "name": "ant2", "antId": 2, "colId": "colony1", "myAntJobs": ["findFood", "workHard", "carryFood", "feedQueen"] }
{ "name": "ant3", "antId": 3, "colId": "colony2", "myAntJobs": ["childCare", "cutLeaves", "feedQueen"] }
but I get E QUERY [js] Error: need an object instead. I'm guessing it wants me to put something like:
$set: {
"myAntJobs": {
"myJobs": col.jobsArray
}
}
Won't this make all of the arrays on the ants into objects with one field? Or am I thinking of this the wrong way...
The biggest issue is I don't really have a space for testing (although I put so much effort into making this question, I could probably use what I just typed out lol).
Can someone functionally explain how the $set works in this context? Also if you know of a better way to add an array to resultant docs in a forEach more effectively, please tell me. But I'd like to understand $set in this context first and foremost.

How can I paginate a document array in mongoose using aggregate?

I want to paginate an array of documents called "Reviews" but I can't find a way to do it, since the code I execute paginate the documents for me and not the array of documents "Reviews".
Code you tried to run
return await this.animeModel
.aggregate()
.match({ _id: Types.ObjectId(reviewPaginateData.animeId) })
.unwind('$reviews')
.group({
_id: '$_id',
reviews: { $push: '$reviews' },
})
.sort(reviewPaginateData.sort)
.limit(reviewPaginateData.limit)
.skip(reviewPaginateData.limit * reviewPaginateData.skip)
.exec();
Document structure
Any way to solve this problem? Thank you very much in advance.
I don't have much experience with mongoose, but I can write a shell query to perform the pagination on an array. So, that you can integrate it in mongoose.
The reason you are not able to paginate is that you are applying the skip and limit after group which is giving you an array as output. So, to apply pagination on the array itself you need to use $slice for more read here
db.collection.aggregate([
{
$match:{
"_id":ObjectId("xyz")
}
},
{
$unwind:"$reviews"
},
{
$group:{
"_id":"$_id",
"reviews":{
$push:"$reviews"
}
}
},
{
$sort:{
sort_value:1
}
},
{
$project:{
"reviews":{
$slice:[
"$reviews",
skip_value,
limit_value
]
}
}
}
]).pretty()
Hope this will help :)

Solr 6 How to change response fields

5.1 i need to change filed value of json response how can i do?
Example below
{
responseHeader: {
status: 0,
QTime: 2
},
response: {
numFound: 1,
start: 0,
docs: [
{
Id: "111445",
name: "TEST",
}
]
}
}
I need to change response to studentList and docs to students like below
{
responseHeader: {
status: 0,
QTime: 2
},
StudentList: {
numFound: 1,
start: 0,
Students: [
{
Id: "111445",
name: "TEST",
}
]
}
}
Please could you help us to resolve this issue.?
There is one way to do it purely on the side of Solr - you need to implement org.apache.solr.response.QueryResponseWriter, in a similar to org.apache.solr.response.JSONResponseWriter, but somehow overriding the field names in the response and provide your own values.
However, I'm 100% sure, that it will be much better option to do your task outside of the Solr (on the side of the service or even on the side of frontend), by just updating response with needed tags.

Resources