Update existing certain documents in MongoDB collection without remove - php

I am new in mongoDB so I need some help with this.
I have a collection for back up. It contains documents with following data:
{
"_id" : ObjectId("59f18942e7798954dc373b67"),
"category" : "building",
},
{
"_id" : ObjectId("59f18942e7798954dc373b68"),
"category" : "building",
},
{
"_id" : ObjectId("59f18942e7798954dc373b69"),
"category" : "tree",
"type" : 18,
},
{
"_id" : ObjectId("59f18942e7798954dc373b70"),
"category" : "book",
"type" : 18,
}
Then, for example, some of objects were changed and became like that:
{
"_id" : ObjectId("59f18942e7798954dc373b67"),
"category" : "building",
"size" : 100
},
{
"_id" : ObjectId("59f18942e7798954dc373b68"),
"category" : "building",
"size" : 400
},
{
"_id" : ObjectId("59f18942e7798954dc373b70"),
"category" : "book",
"type" : 18,
"title" : "New"
}
So I need to update them in my DB. Just replace, as I understood. I've read the docs about using 'upsert' and 'multi'. But I can't implement it.
How to do that?

Basic syntax for updating document in mongo is
db.collection.update(query,update,options);
For your question,
1.
db.collection.update({_id: ObjectId("59f18942e7798954dc373b67")},{$set:{size:100}});
2.
db.collection.update({_id: ObjectId("59f18942e7798954dc373b68")},{$set:{size:400}});
3.db.collection.update({_id: ObjectId("59f18942e7798954dc373b70")},{$set:{title:"New"}});
EDIT:
You can try out this, If you want to perform Write operation in one command:
> db.characters.bulkWrite(
> [
> { updateOne :
> {
> "filter" : { _id : ObjectId("59f18942e7798954dc373b67") },
> "update" : { $set : { size : 100 } }
> }
> },
> { updateOne :
> {
> "filter" : { _id : ObjectId("59f18942e7798954dc373b68") },
> "update" : { $set : { size : 400 } }
> }
> },
> { updateOne :
> {
> "filter" : { _id : ObjectId("59f18942e7798954dc373b68") },
> "update" : { $set: { title: "New"} }
> }
> },
> ]
>);

Related

Reading data from an array with json

In a php script I have the following
$jsonurlpers = "https://api.openarch.nl/1.1/records/show.json?archive=nha&identifier=8554bfba-9fd9-4ca2-876c-feb7da095d6c";
$jsondatapers = file_get_contents($jsonurlpers);
That string I want to decode with the next command
$jsonpers = json_decode($jsondatapers ,true)[0];
But somewhere it did not work...
When I go to to the #jsonulpers I see :
Event
EventType "Overlijden"
EventDate
Year "1901"
Month "7"
Day "7"
EventPlace
Place "Egmond-Binnen"
RelationEP
Can some one tell me how I can read the value behind EventType in a variable? I tried different options but none works...
Thanks,
Fred
I did try this
e.g.
$itemevent = $jsonpers['Event'];
$itemeventtype = $itemevent['EventType']);
abs I thought
$itemeventtype would have a value of "Overlijden", but it was empty
The (json-)output from the url you gave looks like this:
{
"Event" : {
"EventType" : "Overlijden",
"EventDate" : {
"Month" : "7",
"Day" : "7",
"Year" : "1901"
},
"EventPlace" : {
"Place" : "Egmond-Binnen"
}
},
"RelationEP" : [
{
"RelationType" : "Overledene",
"EventKeyRef" : "Event1",
"PersonKeyRef" : "Person1"
},
{
"PersonKeyRef" : "Person2",
"RelationType" : "Vader",
"EventKeyRef" : "Event1"
},
{
"PersonKeyRef" : "Person3",
"RelationType" : "Moeder",
"EventKeyRef" : "Event1"
}
],
"Source" : {
"SourcePlace" : {
"Place" : "Egmond-Binnen / Egmond-Binnen"
},
"SourceAvailableScans" : {
"Scan" : {
"Uri" : "https://nha.blob.core.windows.net/scans/BS%20Overlijden/Egmond-Binnen/1901/RNH_O_EGB_1901_006-a.jpg",
"OrderSequenceNumber" : "1"
}
},
"SourceLastChangeDate" : "2015-07-31",
"SourceRemark" : {
"Value" : "Datadump ExportBS+Overlijden_20210302_102010.csv van NHA via e-mail"
},
"SourceReference" : {
"InstitutionName" : "Noord-Hollands Archief",
"DocumentNumber" : "14",
"Place" : "Haarlem"
},
"RecordGUID" : "{8554bfba-9fd9-4ca2-876c-feb7da095d6c}",
"SourceIndexDate" : {
"To" : "1901-12-31",
"From" : "1901-01-01"
},
"SourceDate" : {
"Year" : "1901",
"Month" : "7",
"Day" : "8"
},
"SourceType" : "BS Overlijden"
},
"Person" : [
{
"BirthPlace" : {
"Place" : "Egmond-Binnen"
},
"PersonName" : {
"PersonNameLastName" : "Baltus",
"PersonNameFirstName" : "Aafje"
},
"Gender" : "Vrouw",
"Age" : {
"PersonAgeYears" : "8 maanden"
}
},
{
"PersonName" : {
"PersonNameFirstName" : "Jan",
"PersonNameLastName" : "Baltus"
}
},
{
"PersonName" : {
"PersonNameLastName" : "Kuijper",
"PersonNameFirstName" : "Grietje"
}
}
]
}
After "Person":, you see a [, which means there is an array of Persons.
The first person does have a "BirthPlace", for the other persons it seems to be unknown what the "BirthPlace" is, because it is not mentioned in the json.
print($jsonpers["Person"][0]["PersonName"]["PersonFirstName"] should be: "Aafje"
and
print($jsonpers["Person"][2]["PersonName"]["PersonFirstName"] should be: "Grietje"

I have to insert nested document batch field into parent document when user select "_id" using mongodb driver manager

following is medicinename collection
{
"_id" : ObjectId("5e25cc9c1e48000083005337"),
"medicine_name" : "nicip",
"potencyy" : "2mg",
"login_id" : ObjectId("5e2166cc58c10dfdfd90e4c5"),
"medicine_type" : {
"medicine_type_id" : ObjectId("5e21e0a71c7f00009b001206"),
"medicine_type_nm" : "tablet"
},
"unit" : {
"unit_id" : ObjectId("5e25cc871e48000083005336"),
"unit_name" : "qty qty"
}
}
following is expected output....
{
"_id" : ObjectId("5e25cc9c1e48000083005337"),
"medicine_name" : "nicip",
"potencyy" : "2mg",
"login_id" : ObjectId("5e2166cc58c10dfdfd90e4c5"),
"medicine_type" : {
"medicine_type_id" : ObjectId("5e21e0a71c7f00009b001206"),
"medicine_type_nm" : "tablet"
},
"unit" : {
"unit_id" : ObjectId("5e25cc871e48000083005336"),
"unit_name" : "qty qty"
}
"batch" : {
"batch_id" : ObjectId("5e25cc871e48000083006337"),
"batch_no" : "abc123",
"mrp" : "600"
}
}

Parse json with PHP. Getting Undefined property: stdClass errors

I am having some issues parsing a json file from Jenkins using PHP
{
"actions" : [
{
"causes" : [
{
"shortDescription" : "Started by an SCM change"
}
]
},
{
},
{
},
{
"buildsByBranchName" : {
"origin/release_5.6.0" : {
"buildNumber" : 242,
"buildResult" : null,
"marked" : {
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"branch" : [
{
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"name" : "origin/release_5.6.0"
}
]
},
"revision" : {
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"branch" : [
{
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"name" : "origin/release_5.6.0"
}
]
}
},
"origin/release_5.7.0" : {
"buildNumber" : 315,
"buildResult" : null,
"marked" : {
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"branch" : [
{
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"name" : "origin/release_5.7.0"
}
]
},
"revision" : {
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"branch" : [
{
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"name" : "origin/release_5.7.0"
}
]
}
},
I have tried doing the following
//Read in JSON object
$json_file2 = file_get_contents('url.com/json');
//Decode JSON file
$test = json_decode($json_file2); //object
//print_r($json_file2);
echo $test->causes;
I am also trying to access the different sections in "buildsByBranchName". I have tried many different variations of the code above, but I keep getting "Undefined property: stdClass" errors.
You are not accessing that value properly. causes resides under actions which is an array. Your code also won't work because causes is an array.
// This is an array so you can't use echo here.
$causes = $test->actions[0]->causes;
// echo out the shortDescription
echo $causes[0]->shortDescription;
or
echo $test->actions[0]->causes[0]->shortDescription;

How to order a mongoDB query by a field in an embedded document?

I have these documents in a mongoDB:
/* 1 */
{
"_id" : ObjectId("553ce99a39108e2b7c1edeb9"),
"coleccion" : "aplicaciones",
"nombre" : "Mascotas",
"descripcion" : "Censo de mascotas",
"tipo" : "privada"
}
/* 2 */
{
"_id" : ObjectId("553e316e39108e802a1edeb9"),
"coleccion" : "aplicaciones",
"nombre" : "otra aplicacionn",
"descripcion" : "w aplicacion",
"tipo" : "privada",
"campoId" : [
{
"id" : "1430145364",
"id_campo" : "553bffca39108eb163cff7aa",
"orden" : 90
},
{
"id" : "1430145368",
"id_campo" : "553bffed39108e346ccff7ab",
"orden" : 100,
"estado" : "0"
},
{
"id" : "1430145370",
"id_campo" : "553c001139108ebc63cff7aa",
"orden" : 29,
"estado" : "1"
},
{
"id" : "1430145395",
"id_campo" : "553c001139108ebc63cff7aa",
"orden" : 9,
"estado" : "0"
}
]
}
I need to query and sort the data in ascending order of each document using the field " campoId.orden " and have executed this query:
db.getCollection('aplicaciones').find({}).sort({'campoId.orden' : -1})
but I do not get the order I want.
can anyone suggest me a way?
In your documents orden in nested array, so you should use mongo aggregation. So below step will follow :
1> First check campoId exits or not $exists
2> Then unwind campoId array $unwind
3> Then group all fields $group
So query as below :
db.aplicaciones.aggregate({
"$match": {
"campoId": {
"$exists": true // check here campoId presents or not using exists
}
}
}, {
"$unwind": "$campoId" // unwind campoId array
}, {
"$sort": {
"campoId.orden": -1
}
},
//groups all fields
{
"$group": {
"_id": "$_id",
"coleccion": {
"$first": "$coleccion"
},
"nombre": {
"$first": "$nombre"
},
"descripcion": {
"$first": "$descripcion"
},
"tipo": {
"$first": "$tipo"
},
"campoId": {
"$push": "$campoId"
}
}
}).pretty()

Find a document with Doctrine ODM with equals condition on nested array of objects

I got this kind of document:
{
"_id" : ObjectId("54ad5c3b9a703a3c088b4567"),
"hard" : 750,
"coordinates" : {
"x" : 0.2388169910939489,
"y" : 0.7996551291084174
},
"indicator" : 500,
"networkIdList" : {
"networkIdData" : [
{
"networkId" : "abc123",
"type" : "SomeNetwork"
},
{
"networkId" : "123asdf",
"type" : "AnotherNetWork"
},
{
"networkId" : "abc123",
"type" : "OneMoreNetwork"
}
]
}
}
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork".
I have tried With this instruction:
$this->documentManager->createQueryBuilder('Mydocument') ->field('networkIdList.networkIdData.$.networkGamingId')->equals('abc123') ->field('networkIdList.networkIdData.$.type')->equals('')
->getQuery()
->execute());
But the cursor return no data.
I also try with
->where("function() {return this.networkIdList.networkIdData.$.networkGamingId == 'abc123'}")
but in this case i got an error that says the Object $ has no propierties.
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork"
$qb = $dm->createQueryBuilder('Foo')
->field('networkIdList.networkIdData.networkId')->equals('abc123')
->field('networkIdList.networkIdData.type')->equals('SomeNetwork');

Categories