Mongodb How to delete/clear an array in an other array - arrays

I would like to now how you can delete/clear an entire array that is inside another array.
This is how my data looks like. I would like to know how i can clear out the array "companyvote". Any suggestions?
{
"_id" : ObjectId("55529cbb056565e80d963fac"),
"email" : "test#test.be",
"img" : "\img\1920x12001431477435530.jpg",
"companyvote" : [
"Lovely inc",
"Behond imagination"
],
"__v" : 0
}

You can use $unset to remove the property like this
db.companies.update({ "_id" : ObjectId("55529cbb056565e80d963fac")},
{$unset:{'companyvote':1}});
Or if you just want to clear the content of the array you can use $set
db.companies.update({ "_id" : ObjectId("55529cbb056565e80d963fac")}, {$set:{'companyvote':[]}})
To delete contents for all record, you just need to remove the filter by Id
db.companies.update({}, {$set:{'companyvote':[]}})

This is what really worked for me.
socket.on('deleteAllVotes', function() {
Slides.find().exec(function(err, b) {
for(var i = 0; i < b.length; i++) {
var allslides = b[i].companyvote;
Slides.update({companyvote:allslides}, {$set:{'companyvote':[]}},function(err, b) {});
}
});
socket.emit('deleteAllVotes');
});

You can clear the content of array for one record with
db.companies.update({ _id : ObjectId("55529cbb056565e80d963fac")}, {$set:{'companyvote':[]}});
or
db.companies.update({ "_id" : ObjectId("55529cbb056565e80d963fac")}, {$unset:{'companyvote':1}});
If you want to clear multi record, don't forget to add option
db.companies.update({}, {$set:{'companyvote':[]}}, {multi: true});
or
db.companies.update({}, {$unset:{'companyvote':1}}, {multi: true});

Related

MongoDB: Check for missing documents using a model tree structures with an array of ancestors

I'm using a model tree structures with an array of ancestors and I need to check if any document is missing.
{
"_id" : "GbxvxMdQ9rv8p6b8M",
"type" : "article",
"ancestors" : [ ]
}
{
"_id" : "mtmTBW8nA4YoCevf4",
"parent" : "GbxvxMdQ9rv8p6b8M",
"ancestors" : [
"GbxvxMdQ9rv8p6b8M"
]
}
{
"_id" : "J5Dg4fB5Kmdbi8mwj",
"parent" : "mtmTBW8nA4YoCevf4",
"ancestors" : [
"GbxvxMdQ9rv8p6b8M",
"mtmTBW8nA4YoCevf4"
]
}
{
"_id" : "tYmH8fQeTLpe4wxi7",
"refType" : "reference",
"parent" : "J5Dg4fB5Kmdbi8mwj",
"ancestors" : [
"GbxvxMdQ9rv8p6b8M",
"mtmTBW8nA4YoCevf4",
"J5Dg4fB5Kmdbi8mwj"
]
}
My attempt would be to check each ancestors id if it is existing. If this fails, this document is missing and the data structure is corrupted.
let ancestors;
Collection.find().forEach(r => {
if (r.ancestors) {
r.ancestors.forEach(a => {
if (!Collection.findOne(a))
missing.push(r._id);
});
}
});
But doing it like this will need MANY db calls. Is it possible to optimize this?
Maybe I could get an array with all unique ancestor ids first and check if these documents are existing within one db call??
First take out all distinct ancesstors from your collections.
var allAncesstorIds = db.<collectionName>.distinct("ancestors");
Then check if any of the ancesstor IDs are not in the collection.
var cursor = db.<collectionName>.find({_id : {$nin : allAncesstorIds}}, {_id : 1})
Iterate the cursor and insert all missing docs in a collection.
cursor.forEach(function (missingDocId) {
db.missing.insert(missingDocId);
});

Add data to array within array in MongoDB

So heres my mongodb document:
{
"_id" : "",
"lists" : [
{
"name" : "list 1",
"items" : []
},
{
"name" : "list 2",
"items" : []
}
]
}
How would I go about adding an object inside "items"?
This is the code I have so far, but it doesn't work:
xxx.update(_id, {$push: { "lists.$.items": item}});
Note that I have access to the index (variable called 'index'), so its possible to insert an item at index, 0, 1, 2..., etc.
I tried this before, but it won't work:
xxx.update({_id, "lists": index}, {$push: { "lists.$.items": item}});
I also looked at other similar questions and couldn't find anything. Most of them have some sort of id field in their arrays, but I don't.
What about
xxx.update({_id}, {$push: { "lists.index.items": item}});
Of course this would fail, what I mean is replace index with real index values
xxx.update({_id}, {$push: { "lists.2.items": item}});
You can manipulate the update json based on the index maybe as below.
var update = '{$push: { "lists.'+index+'.items": '+item+'}}';
var updateObj = JSON.parse(update);
xxx.update({_id}, updateObj);
Not sure if it will work as it is or it would need further tweaking, but you get the idea.

Get index of array item if item of array equals name

I have an array of items like this:
{
"dateAdded" : "2016-02-09 12:41:37",
"customValue" : "5",
"name" : "highestHeight"
},
{
"dateAdded" : "2016-02-09 12:41:37",
"customValue" : "46.91",
"name" : "highestWeight"
},
{
"dateAdded" : "2016-02-09 12:41:37",
"customValue" : "14972.02",
"name" : "highestScore"
},
I would like to get the items associated with the item that has the name = highestScore but not sure how or even what I should be searching for to find an example.
How about starting with the documentation on Array, which will show that it implements the CollectionType protocol, which has a filter function:
myArray.filter({ $0.name == "highestScore" })
That assumes it is an array of objects/types, and not an array of Dictionary instances. If that was the case, then you would use:
myArray.filter({ $0["name"] == "highestScore" })
You can look at functional filtering here: http://www.raywenderlich.com/82599/swift-functional-programming-tutorial
Do something like:
highscoreArray= yourArray.filter { (dictionary) in dictionary["name"]! == "highestScore" }
Haven't tested it but it should be along of the lines of that.

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?

Removing the array element in mongoDB based on the position of element

Actually I need to remove an element from the array based on its position. Using $pop we can remove element from top or bottom (considering it as a stack. 0th element at top) as explained here.
We can also remove element from array based on the value of the elements in the array using $pull as explained here.
But I need to remove element from the array based on position. So is there any way I can do this.
From documentation:
{ $pull : { field : {$gt: 3} } } removes array elements greater than 3
So i suppose that you can do somethig like this for now:
{ $pull : { field : {$gt: 3, $lt: 5} } } // shoud remove elemet in 4 position
Or try update using position operator, i suppose shoud be something like this:
{ $pull : "field.4" }
{ $pull : {"field.$": 4}}
It is only a suggestion, because i can't test it right now.
Update:
Seems you cant do it right know in one step(there is such bug in jira)
But you can remove using unset element in position and that pull elemets with null value:
{$unset : {"array.4" : 1 }}
{$pull : {"array" : null}}
That is how possible to do that with latest mongodb v4.2, ugly but working
_id: ObjectId("5e4539cb6aebbeaa0a6b8fe7")
}, [
{ $set:
{ notes:
{
$concatArrays: [
{ $slice: ['$notes', 4] },
{ $slice: ['$notes', { $add: [1, 4] }, { $size: '$notes' }]}
]
}
}
}
])```
Here's your answer: MongoDB pull array element from a collection
To remove specific element from an array of some document first you need to identify this element. For instance I have a document with array and every element of this array is an object:
{
"_id" : ObjectId("5140f34888dd50971900002d"),
"_permissions" : {
"edit" : [
{
"profile_id" : NumberLong(123),
"comment" : "app/project owner"
},
{
"profile_id" : NumberLong("153579099841888257"),
"comment" : "project admin"
},
{
"profile_id" : NumberLong("153579095869882369"),
"comment" : "project admin"
}
],
"view" : [
{
"profile_id" : NumberLong(123),
"comment" : "app/project owner"
},
{
"profile_id" : NumberLong("153579099841888257"),
"comment" : "project admin"
},
{
"profile_id" : NumberLong("153579095869882369"),
"comment" : "project admin"
}
]
}
}
So let's remove profile_id with "153579099841888257" value from _permissions.view array.
Here we go
db.collection.update({_id: ObjectId("5140f34888dd50971900002d")}, {$pull:{"_permissions.view": {"profile_id": NumberLong("153579099841888257")}}});
I define scope of the object (to make sure id doesn't affect any other first found document)
Identify needed element to pull out: profile_id with "153579099841888257" value in the _permissions.view array

Resources