Meteor Mongodb Bulk Update by _id not working - mongodb

I'm trying to perform following bulk Update Operation by _id:
let bulk = Transactions.rawCollection().initializeOrderedBulkOp();
transactions.forEach((t) => {
let query = { '_id' : new Meteor.Collection.ObjectID(t._id._str) };
bulk.find( query ).update( { $set: { balance: t.balance, updated_at: new Date() } } );
});
bulk.execute(Meteor.bindEnvironment((err, res) => {
if (!err) {
callback(null, true);
} else {
console.log("Error Ocurred");
callback(true, null);
}
}));
But This find query by _id is not working. If I do query by any other field It works just fine. But I can't do that because Collection has only one Unique field as '_id'.
EDITED:
Following is Transaction MongoDB Document
{
"_id" : ObjectId("5899f8a15d79b02f6075100d"),
"transaction" : "Charge",
"description" : "01/01/2017 - 01/28/2017",
"created_by" : "SYSTEM",
"residency_id" : "6pFs3sBMZPtp3e5N9",
"value" : 25.82,
"balance" : 25.82,
"created_at" : ISODate("2017-02-07T16:41:05.718+0000"),
"updated_at" : ISODate("2017-02-07T18:08:05.378+0000")
}
Help Needed. TIA

Related

Mongo DB UpdateOne with c#

I've got this data in mongodb
{"_id" : "pippo",
"Rich" : [
{
"_id" : "8c9379f1-ba5a-4b43-b7ad-f5fe3bf6f09d",
"Appr" : null
},
{
"_id" : "8c9379f1-265a-4b43-b7ad-f5fe3bf6f09d",
"Appr" : null
}
]},
{"_id" : "pluto",
"Rich" : [
{
"_id" : "8c9379f1-ba5a-4b43-b7ad-f5fe3bf6f09d",
"Appr" : null
},
{
"_id" : "8c9379f1-265a-4b43-b7ad-f5fe3bf6f09d",
"Appr" : null
}
]},
How can i update, with the command UpdateOne, in document "Pippo" the property "Appr" inside the array "Rich" having "_id" 8c9379f1-265a-4b43-b7ad-f5fe3bf6f09d?
thank you
Bruno
UPDATE
I try this
var filter = Builders<RichiestaGiornalieri>.Filter.Eq("id", Pippo);
var update = Builders<RichiestaGiornalieri>.Update.Set("rich.appr", new[] { new Approvazione() { Approvata = true",
Approvatore = User.Identity.Name,
DataApprovazione = DateTime.Now,
id = Guid.NewGuid().ToString(),
Note = "" }
});
var arrayFilters = new List<ArrayFilterDefinition> { new JsonArrayFilterDefinition<RichiestaGiornalieri>("{'rich.id':'8c9379f1-265a-4b43-b7ad-f5fe3bf6f09d'}") };
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
dbRichieste.UpdateOne(filter, update, updateOptions);
But i receive this error messagge
MongoBulkWriteException`1: A bulk write operation resulted in one or more errors.
The array filter for identifier 'rich' was not used in the update { $set: { rich.appr: [ { DataApprovazione: new Date(1599579246919), _id: "2a5cc55e-70e8-4138-ace2-6b5131cd4a9a", Approvata: true, Approvatore: "Pippo", Note: "" } ] } }

Remove by _id inside a nested array, inside of a collection

this is my mongoDb footballers collection :
[
{
"_id" : ObjectId("5d83b4a7e5511f28847f1884"),
"prenom" : "djalil",
"pseudo" : "dja1000",
"email" : "djalil#gmail.com",
"selectionned" : [
{
"_id" : "5d83af3be5511f28847f187f",
"role" : "footballeur",
"prenom" : "Gilbert",
"pseudo" : "Gilbert",
},
{
"_id" : "5d83b3d5e5511f28847f1883",
"role" : "footballeur",
"prenom" : "Xavier",
"pseudo" : "xav4544",
}
]
},
{
"_id" : ObjectId("5d83afa8e5511f28847f1880"),
"prenom" : "Rolande",
"pseudo" : "Rolande4000",
"email" : "rolande#gmail.com",
"selectionned" : [
{
"_id" : "5d83b3d5e5511f28847f1883",
"role" : "footballeur",
"prenom" : "Xavier",
"pseudo" : "xav4544",
}
]
}
}
How could I delete each selectionned people who has the 5d83b3d5e5511f28847f1883 _id through all of the collection?
I do need xavier to deseappear from any 'selectionned' array , just like doing a 'delete cascade' in SQL language
This is what I've tried with no luck :
function delete_fb_from_all(fb){
var ObjectId = require('mongodb').ObjectID; //working
var idObj = ObjectId(fb._id); //working
try {
db.collection('footballers').remove( { "selectionned._id" : idObj } );
console.log('All have been erased');
} catch (e) {
console.log(e);
}
}
And this too is not working :
db.collection('footballers.selectionned').remove( { "_id" : idObj } );
i really dont know how to do this.
i'm trying out this right now :
db.collection.update({'footballers.selectionned': idObj }, {$pull: {footballers:{ selectionned: idObj}}})
This is the error :
TypeError: db.collection.update is not a function
I think that the solution is maybe there :
https://docs.mongodb.com/manual/reference/operator/update/pull/#pull-array-of-documents
EDIT 1
i'm currently trying ou this :
var ObjectId = require('mongodb').ObjectID; //working
var idObj = ObjectId(fb._id); //working
try {
db.collection('footballers').update(
{ },
{ $pull: { selectionned: { _id: idObj } } },
{ multi: true }
)
} catch (e) {
console.log(e);
}
SOLVED :
Specifiying the email, it is now working, I guess the problem was comin from the _id field :
try {
db.collection('footballers').update(
{ },
{ $pull: { selectionned: { email: fb.email } } },
{ multi: true }
)
} catch (e) {
console.log(e);
}
Object ID :
The issue is may be on your object id creation. No need to make string-id with mongoDB object id.
// No need
var ObjectId = require('mongodb').ObjectID;
var idObj = ObjectId(fb._id);
// do as normal string
db.collection('footballers').remove( { "selectionned._id" : fb._id } );

MongoDB update only a few records, create a new attribute, assign a value

I wasn't lucky finding any help on this anywhere else.
Basically I want to update only the few documents that do not have a given attribute already.
And the value for the update comes from a field that is already on the document.
This is what I tried but it didn't like the "from a field already on the document" part. Saying Cn doesn't exist.
db.getCollection('test').update(
// query
{ "id2" : { $exists: false } },
// update
{ id2: Cn },
// options
{
"multi" : true, // update all documents
"upsert" : false // don't insert new documents
}
);
Here is my test data
/* 1 */
{
"_id" : ObjectId("5912132c4a58677726d37168"),
"Cn" : "CA",
"id2" : "CAAB",
"Prov" : "AB"
}
/* 2 */
{
"_id" : ObjectId("591213404a58677726d37172"),
"Cn" : "CA",
"id2" : "CANZ",
"Prov" : "NZ"
}
/* 3 */
{
"_id" : ObjectId("591213534a58677726d37180"),
"Cn" : "CA",
"id2" : "CAMB",
"Prov" : "MB"
}
/* 4 */
{
"_id" : ObjectId("591213674a58677726d3718c"),
"Cn" : "US"
}
/* 5 */
{
"_id" : ObjectId("591213894a58677726d371a3"),
"Cn" : "MX"
}
All this should do is create a id2 on US & MX and give those new id2 attributes the corresponding values 'US' & 'MX'.
This would not be a big deal but I have able 144 countries & 10,000+ documents to add id2 to.
You can't update multiple items with an operator that only contains expressions, and self referencing doesn't work either.
Check out this question for work around solutions to get what you need done: Update MongoDB field using value of another field
You can try this :
db.your_collection.aggregate( [
{ $match : { id2 : { $exists: false }}},
{ $addFields: {
id2 : "$Cn"
}
},
{ $out : "your_collection" }
]);
This will remove all documents in collection which have id2 field.
You can do this in mongoose in a longer way :
db.getCollection('test').find({ "id2" : { $exists: false } }, function(err, docs){
if(err){
//handle errror
}
else if(!docs){
// no docs found
}
else{
for(var i=0; i< docs.length; i++){
db.getCollection('test')
.findByIdAndUpdate(
docs[i]._id
, { $set : { id2 : docs[i].Cn}}
, { new : true}
, function(err, doc){
if(err){
//handle error
}
else{
//doc was updated
}
});
}
}
});
I would not have gotten to this without Mihir Bhende pushing. Thanks for that.
var c = db.getCollection('test').find(
{ "id2" : { $exists: false }}
);
c.forEach(function(myDoc) {
print("doc", myDoc.Cn);
db.getCollection('test').update( {_id: myDoc._id}, {$set: { "id2": myDoc.Cn }}, function (err) {
if (err) { print("err"); }
});
});

Upserting on embedded document

I have the following document strucutre
{
"_id" : "NmBYYasdsa",
"objectId" : "asdsd"
"text" : "test",
....
"publishedAt" : ISODate("2015-05-28T15:31:51Z"),
"updatedAt" : ISODate("2015-05-28T15:31:51Z"),
"data" : {
.....
"likeCount" : 0,
"replyCount" : 0
}
}
That is use to synchronise my database with an external API. To do this, I poll the API once every minute and do a bulk upsert, matching on the object id to keep my database up to date.
Problem is that the data subdocument doesn't get updated when upserting, any ideas as to why?
My bulkwrite method
Mongo.Collection.prototype.upsertBulk = function(matcher, documents, options) {
if (_.isEmpty(documents)) { throw Error('Empty list of documents provided'); }
options = options || {};
var operations = documents.map(function(_document) {
_document._id = Random.id();
var operation = {
updateOne: {
filter: {},
update: { $set: _document },
upsert: true
},
};
operation['updateOne']['filter'][matcher] = _document[matcher];
return operation;
});
this.__mongoCollection(function(collection) {
collection.bulkWrite(operations, options, function(error, result) {
if (error) { throw error; }
return result;
});
});
};

Mongodb: Finding and updating object property from array

I have a collection with multiple documents which follow this structure:
{
"_id" : {
"oid" : XXX
},
"name" : "Name",
"videos" [
{
"id" : 1,
"thumbnail" : "thumbnail.jpg",
"name" : "Name here"
},
{
"id" : 2,
"thumbnail" : "thumbnail.jpg",
"name" : "Name here"
},
{
"id" : 3,
"thumbnail" : "thumbnail.jpg",
"name" : "Name here"
}
]
}
I want to find and update the a thumbnail of a video, of which I only know the id, but not which document it is in.
This is what I've tried so far, but it's not working properly. All the examples I found relied on knowing the document id, and the array position of the object to update. I also found that doing a query like this found the document okay, but set the whole document as the new thumbnail!
db.collection(COLLECTION-NAME, function(err, collection){
collection.update(
{ 'videos.id' : 2 },
{ $set: { thumbnail: "newThumbnail.jpg" } },
function(err, result){
if (!err){
console.log('saved', result)
} else {
console.log('error', err);
}
}
);
});
Use the $ positional operator to update the value of the thumbnail field within the embedded document having the id of 2:
db.collection.update(
{ "videos.id": 2 },
{ "$set": { "videos.$.thumbnail" : "newThumbnail.jpg" } }
)