Rename a sub-document field within an Array of an Document - database

I am trying to rename the particular child field inside an array of an collection in MONGODB
{
"_id" : Id("248NSAJKH258"),
"isGoogled" : true,
"toCrawled" : true,
"result" : [
{
"resultsId" : 1,
"title" : "Text Data to be writen",
"googleRanking" : 1,
"isrelated" : false
},
{
"resultId" : 2,
"title" : "Text Data",
"googleRanking" : 2,
"isrelated" : true
}]
**I need to rename "isrelated" to "related" ** from the collection document
Using mongo Version 4.0
I Tried :
db.collection_name.update({}, { $rename: { 'result.isrelated': 'result.related'} } )
But it didn't worked in my case

As mentioned in official documentation $rename not working for arrays.
Please check link below:
https://docs.mongodb.com/manual/reference/operator/update/rename/
But you can do something like this
let newResult = [];
db.aa1.find({}).forEach(doc => {
for (let i in doc.result) {
newResult.push({
"resultsId" : doc.result[i]['resultsId'],
"title" : doc.result[i]['title'],
"googleRanking" : doc.result[i]['googleRanking'],
"related" : doc.result[i]['isrelated'],
})
}
db.aa1.updateOne({_id: doc._id}, {$set: {result: newResult}});
newResult = []
})

Related

Delete collection in mongodb

I have the following json file in mongodb:
{
"_id" : ObjectId("59de156faf75d539b47e8db3"),
"user" : "user1",
"item" : {
"32a1fsd32asfd65asdf65" : {
...
},
"32a1fsd32asfd555" : {
}, ...
}
}
I want to perform a query and delete one of the two items. As a matter of fact, my database contains several users. Therefore, in order to retrieve the specific one from the mongodb i am performing the following:
How can I retrieve also a specific item and delete all its fields (for example 32a1fsd32asfd65asdf65)?
Based on the example document provided in your document it looks like you want to remove an attribute of the subdocument item.
You can use the $unset update operator:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// unset the attribute named "sfd65asdf65"
{$unset: {'item.sfd65asdf65': 1}}
)
Given the document provided in your question, the above command will cause that document to be updated to:
{
"_id" : ObjectId("59de156faf75d539b47e8db3"),
"user" : "user1",
"item" : {
"sd32asfd555" : {
...
}
}
}
If you want to remove the item attribute entirely then you would run:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// unset the attribute named "32a1fsd32asfd65asdf65"
{$unset: {'item': 1}}
)
And if you want to empty the item attribute (i.e. remove all of its attributes but retain the item attribute) then you would run this command:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// overwrite the "item" attribute with an empty sub document
{$set: {'item': {}}}
)
You can find more examples in the docs.
Say we have some users:
> db.test.insert( { _id: 1, user: "bob", field1: 1, field2 :{ field3 : 2 } } )
WriteResult({ "nInserted" : 1 })
> db.test.insert( { _id: 2, user: "fred", field1: 1, field2 :{ field3 : 2 } } )
WriteResult({ "nInserted" : 1 })
We can then use replaceOne to find the user and also then just replace the whole document, thus removing all the fields from that document:
> db.test.replaceOne( { user: "bob"}, { user: "bob" } )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Then our new documents will look like:
> db.test.find()
{ "_id" : 1, "user" : "bob" }
{ "_id" : 2, "user" : "fred", "field1" : 1, "field2" : { "field3" : 2 } }

String from document meets value of array

I've got an array of Project ID's, for example:
[ 'ExneN3NdwmGPgRj5o', 'hXoRA7moQhqjwtaiY' ]
And in my Questions collection, I've got a field called 'project', which has a string of a project Id. For example:
{
"_id" : "XPRbFupkJPmrmvcin",
"question" : "Vraag 13",
"answer" : "photo",
"project" : "ExneN3NdwmGPgRj5o",
"datetime_from" : ISODate("2017-01-10T08:01:00Z"),
"datetime_till" : ISODate("2017-01-10T19:00:00Z"),
"createdAt" : ISODate("2017-01-10T08:41:39.950Z"),
"notificationSent" : true
}
{
"_id" : "EdFH6bo2xBPht5kYW",
"question" : "sdfadsfasdf",
"answer" : "text",
"project" : "hXoRA7moQhqjwtaiY",
"datetime_from" : ISODate("2017-01-11T11:00:00Z"),
"datetime_till" : ISODate("2017-01-11T17:00:00Z"),
"createdAt" : ISODate("2017-01-10T10:21:42.147Z"),
"notificationSent" : false
}
Now I want to return all documents of the Questions collection, where the Project (id) is one of the value's from the Array.
To test if it's working, I'm first trying to return one document.
Im console.logging like this:
Questions.findOne({project: { $eq: projectArray }})['_id'];
but have also tryed this:
Questions.findOne({project: { $in: [projectArray] }})['_id'];
But keep getting 'undefined'
Please try this.
Questions.find({project: { $in: projectArray }}) => for fetching all docs with those ids
Questions.findOne({project: { $in: projectArray }}) => if you want just one doc

AngularFire, access deep child links?

Using latest Angular with Firebase and I'm trying to access somewhat deep nested items from logged in users.
The structure looks something like this:
firebase -> users -> user-uid -> email/name/pass/lists/ (where lists have) -> list-uid -> item-uid -> item-name.
I want to access that last name-child (preferably through an ng-repeat since they're list items and I want them displayed on each users dashboard).
I've been trying different methods but the closest one are this:
$scope.user = $firebaseObject(ref.child('users').child(authData.uid));
And then in my html (for now):
<span>{{user.lists}}</span>
Which prints out something like: {"-uid":{"age":"21", "name":"martin"},{"-uid":{"age":"25", "name":"john"}}} etc etc etc.
The ref goes to:
var ref = new Firebase('https://url.firebaseio.com');
Any ideas? Thanks!
Edit:
I tried to add a ng-repeat like this:
<li ng-repeat="list in user.lists">{{list.name}}</li>
Which somewhat works, it shows me the objects I've put in which are static but not the ones "one level deeper"...
Edit 2:
Updated with .json for structure.
I can get the "me" out of name but not "mjölk" which are a level deeper:
"users" : {
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"email" : "torsten#gmail.com",
"lists" : {
"-KDjNYC8GS2QFHYyp74L" : {
"age" : "other",
"name" : "me"
},
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"-KDjN_NkTQmj_1R00xZL" : {
"done" : false,
"id" : 1458936351305,
"name" : "mjölk"
},
"-KDjN_r0WmT6xiZwadO5" : {
"done" : false,
"id" : 1458936351305,
"name" : "ägg"
},
"-KDjNagkBWmJRj6oQqc2" : {
"done" : false,
"id" : 1458936351305,
"name" : "rejv"
},
"-KDjNb5Fpak_9A_rvn8W" : {
"done" : false,
"id" : 1458936351305,
"name" : "kossor"
},
"-KDjOVtAFJoYVNUkapNC" : {
"done" : false,
"id" : 1458936351305,
"name" : "piss"
},
"-KDjOlemXR2eOoqPBh0v" : {
"done" : false,
"id" : 1458936677873,
"name" : "mjölk igen"
}
}
},
As I said in my comment already: part of your problem is caused by the fact that you are nesting lists. There are many reasons why the Firebase documentation recommends to nest data sparingly and this is one of them.
To unnest the data, you store the user profiles separately from the lists for each user:
"users" : {
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"email" : "torsten#gmail.com",
}
},
"user_lists" : {
"-KDjNYC8GS2QFHYyp74L" : {
"age" : "other",
"name" : "me"
},
"8a6da12a-0992-43f5-bb33-95ddd49fed8c" : {
"-KDjN_NkTQmj_1R00xZL" : {
"done" : false,
"id" : 1458936351305,
"name" : "mjölk"
},
"-KDjN_r0WmT6xiZwadO5" : {
"done" : false,
"id" : 1458936351305,
"name" : "ägg"
},
"-KDjNagkBWmJRj6oQqc2" : {
"done" : false,
"id" : 1458936351305,
"name" : "rejv"
},
"-KDjNb5Fpak_9A_rvn8W" : {
"done" : false,
"id" : 1458936351305,
"name" : "kossor"
}
}
}
Now if you want to show a list of profile and the lists for the current user, you:
var ref = new Firebase('https://yours.firebaseio.com');
$scope.users = $firebaseArray(ref.child('users'));
$scope.lists = $firebaseArray(ref.child('user_lists').child(auth.uid));
And then in your HTML:
<p>Users:</p>
<ul>
<li ng-repeat="user in users">{{user.email}}</li>
</ul>
<p>Lists for you:</p>
<ul>
<li ng-repeat="list in lists">{{list.name}}</li>
</ul>

Mongoose update array property

I am trying to update a document via Mongoose, but it does not update the array property.
Here's an example document:
{
"_id" : "55da477a9bfc910e38zzccf2",
"projectname" : "ASong",
"owner" : "adam",
"tracks" : [{
"name" : "Bass",
"file" : "upload/Bass.mp3",
"volume" : "0.75",
"pan" : "0.65"
}, {
"file" : "upload/Drums.mp3",
"volume" : "0.4",
"pan" : "-0.75",
"name" : "Drums"
}
],
"users" : ["adam", "eve"]
}
if I pass to Mongoose an object and try to use it to update like this:
var id = req.body._id;
var editedProject = req.body;
delete editedProject._id;
console.log("TRACKS: " +JSON.stringify(editedProject.tracks));
Project.update({"_id": id}, editedProject, {"upsert": true}, function(err, proj) {
if (err) {
res.send(err);
}
res.json(proj);
});
Only the 1st level properties are updated, but not the array.
I've found some solutions that involve looping through the array elements and calling an update for each element, but I would like to avoid that and keep the update as a single operation.
Or is it better to avoid using arrays?

MongoDB search using $in array not working

I'm using MongoDB shell version: 2.4.8, and would simply like to know why a nested array search doesn't work quite as expected.
Assume we have 2 document collections, (a) Users:
{
"_id" : ObjectId("u1"),
"username" : "user1",
"org_ids" : [
ObjectId("o1"),
ObjectId("o2")
]
}
{
"_id" : ObjectId("u2"),
"username" : "user2",
"org_ids" : [
ObjectId("o1")
]
}
and (b) Organisations:
{
"_id" : ObjectId("o1"),
"name" : "Org 1"
}
{
"_id" : "ObjectId("o2"),
"name" : "Org 2"
}
Collections have indexes defined for
Users._id, Users.org_id, Organisations._id
I would like to find all Organisations a specific user is a member of.
I've tried this:
> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : [myUser.org_ids] }})
yet it yields nothing as a result. I've also tried this:
> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : myUser.org_ids }})
but it outputs the error:
error: { "$err" : "invalid query", "code" : 12580 }
(which basically says you need to pass $in an array) ... but that's what I thought I was doing originally ? baffled.
Any ideas what I'm doing wrong?
db.collection.find() returns a cursor - according to documentation. Then myUser.org_ids is undefined, but $in field must be an array. Let's see the solution!
_id is unique in a collection. So you can do findOne:
myUser = db.Users.findOne( { _id: ObjectId("u1") })
db.Organisations.find( { _id : { $in : myUser.org_ids }})
If you are searching for a non-unique field you can use toArray:
myUsers = db.Users.find( { username: /^user/ }).toArray()
Then myUsers will be an array of objects matching to the query.

Resources