logo
down
shadow

PHP/MongoDB - $concat aggregation


PHP/MongoDB - $concat aggregation

By : justdust
Date : November 21 2020, 03:00 PM
I wish did fix the issue. Wrong Driver
As noted, you are using the wrong driver to start with. So the very first thing to do is install the correct driver as documented. If you are still confused about which driver is which, then there is this page on php.net with a diagram explaining it all.
code :
$pipeline = [
  [ '$addFields' => [
    'final_value' => [
      '$concat' => [ '$first', ' ', '$last' ]
    ]
  ]],
  [ '$match'=>[
    'final_value'=> new MongoDB\BSON\Regex("/$texto/",'gi')
  ]]
];
$pipeline = [
  [ '$redact' => [
    '$cond' => [
      'if' => [
        '$ne' => [
          [ '$indexOfCP' => [
            [ '$concat' => [ '$first', ' ', '$last' ] ],
            $texto
          ]],
          -1
        ]
      ],
      'then' => '$$KEEP',
      'else' => '$$PRUNE'
    ]
  ]]
];
$collection = (new MongoDB\Client)->test->collection;
$indexName = $collection->createIndex(['first' => 'text', 'last' => 'text' ])
$collection = (new MongoDB\Client)->test->collection;

$cursor = $collection->find([
  '$text' => [ '$search' => $words_or_phrase ]
]);

foreach ($cursor as $document) {
  var_dump($document);  # do something real here
}


Share : facebook icon twitter icon
Mongodb concat not working in aggregation

Mongodb concat not working in aggregation


By : Rus David
Date : March 29 2020, 07:55 AM
will be helpful for those in need You don't necessarily need the $concat operator (i.e. if you're using MongoDB 3.0 and newer), the $dateToString operator does this for you already:
code :
db.leads.aggregate([
    {
        "$project": {           
            "status": 1,
            "stage": 1,
            "todo.title": 1,
            "created": {
                "day": { "$dayOfMonth": "$createdOn" },
                "month": { "$month": "$createdOn" },
                "year": { "$year": "$createdOn" }
            },
            "myDate": { "$dateToString": { "format": "%Y-%m-%d", "date": "$createdOn" } }   
        }
    }
])
db.leads.aggregate([
    {
        "$project": {           
            "status": 1,
            "stage": 1,
            "todo.title": 1,
            "created": {
                "day": { "$substr": ["$createdOn", 8, 2] },
                "month": { "$substr": ["$createdOn", 5, 2] },
                "year": { "$substr": ["$createdOn", 0, 4] }
            }   
        }
    },
    {
        "$project": {
            "_id": 0,
            "status": 1,
            "stage": 1,
            "todo": 1,
            "created": 1,
            "myDate": { 
                "$concat": [
                    "$created.year", 
                    "-", 
                    "$created.month", 
                    "-", 
                    "$created.day"
                ] 
            }       
        }
    }
])
db.leads.aggregate([
    {
        "$project": {
            "_id": 0,           
            "status": 1,
            "stage": 1,
            "todo.title": 1,
            "created": {
                "day": { "$substr": ["$createdOn", 8, 2] },
                "month": { "$substr": ["$createdOn", 5, 2] },
                "year": { "$substr": ["$createdOn", 0, 4] }
            },
            "myDate": { 
                "$concat": [
                    { "$substr": ["$createdOn", 0, 4] }, 
                    "-", 
                    { "$substr": ["$createdOn", 5, 2] }, 
                    "-", 
                    { "$substr": ["$createdOn", 8, 2] }
                ] 
            }       
        }
    }
])
group concat of fields in mongodb in aggregation

group concat of fields in mongodb in aggregation


By : ervin
Date : March 29 2020, 07:55 AM
I wish this helpful for you You can concatenate required values and push to an array during grouping:
code :
db.adsets.aggregate([
    {$group:{
        _id:"$Data.Campaign Name",
        total : {$sum:1},
        myfield: {$push: {$concat:["$Data.URL Tags", "-", "$Data.Ad Name"]}}
        }
    }]
)
db.adsets.aggregate([
    {$group:{
        _id:"$Data.Campaign Name",
        total : {$sum:1},
        myfield: {$addToSet: {$concat:["$Data.URL Tags", "-", "$Data.Ad Name"]}}
        }
    }]
)
How can I concat an array of integer in MongoDB aggregation method?

How can I concat an array of integer in MongoDB aggregation method?


By : user1942743
Date : March 29 2020, 07:55 AM
this will help You can try below aggregation
You can use $toLower aggregation to convert integer to string or $toString if you are using mongodb 4.0
code :
db.collection.aggregate([
  { "$project": {
    "import_hashed": {
      "$let": {
        "vars": {
          "key": {
            "$reduce": {
              "input": "$import_ids",
              "initialValue": "",
              "in": { "$concat": ["$$value", "##", { "$toLower": "$$this" }] }
            }
          }
        },
        "in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
      }
    }
  }}
])
{ "import_hashed": "5200##4710##100 }
MongoDB concat two fields using aggregation where actual field is in an array

MongoDB concat two fields using aggregation where actual field is in an array


By : user3592581
Date : March 29 2020, 07:55 AM
I wish did fix the issue. With below query we're iterating through batchElements.elements & forming objects with type & _id & finally $map would push an array of objects back to batchElements.elements where $addFields would add the field to actual document, Try this :
code :
db.yourCollectionName.aggregate([{
    $addFields: {
        'batchElements.elements': {
            $map:
            {
                input: "$batchElements.elements",
                as: "each",
                in: { type: '$$each.type', '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }
               /** So if you've multiple fields in each object then instead of listing all, You need to use 
                in: { $mergeObjects: ["$$each", { '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }] } */
            }
        }
    }
}])
mongodb aggregation project objectId with concat

mongodb aggregation project objectId with concat


By : dora
Date : March 29 2020, 07:55 AM
This might help you From MongoDB 4.0 and newer, there is a $toString operator which returns the ObjectId value as a hexadecimal string:
Related Posts Related Posts :
  • Composer is not functioning?
  • Retrieving an Array with Axios in Laravel
  • How to get the last child of each cd element?
  • How to allow users to connect their own domain
  • PHP multidimensionnal array and empty value
  • PHP if statement doesn't work properly (paradoxical)
  • BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::searchable()
  • PHP explode() returns array inside an array
  • Echo parse error for creating new php file
  • PHP Parse error: syntax error, unexpected '?'
  • PHP Session not working correctly on a particular host
  • laravel how to get the extremities tables through the pivot
  • Show duplicate value in array only one but show all others
  • SMTP Emails not send (There is something wrong with server config as code is fine for other servers)
  • I can't turn off debug bar in Laravel on production
  • PHP creating multidimensional json
  • Increment value with get
  • Laravel 5.5: Convert query builder to eloquent
  • Reverse proxy onto a WordPress page?
  • Jumble Solver url rewrite
  • Using .htaccess to Execute php if directory of the same name not found
  • mysql - Unknown Column In Where Clause
  • Receive Emails into my Admin panel with php or other
  • PHP - adding only distinct value to an array in foreach loop not working
  • How to pass date picker from one page to another
  • Try catch always return error when I insert 2 data
  • Php redirect not working on submission
  • How to get array value from wordpress database get_results
  • how Automatically go from first.php to second.php
  • uploading file not working in codeigniter 3 error: you did not select any file
  • Yii2, gridview can not show some html tags inside cells
  • What are the thing we need to configure to implement live notification module (using redis and socket.io) in https serve
  • How to handle multi criterias search in PHP
  • PHP - Get maximum key and its value in array
  • PHP: how to retrieve all the metrics and dimensions from the Google Metadata API?
  • Deliver php mails to special-character-email adresses, such as äüö
  • Delete a single row from an MSSQL table from PHP
  • Property [name] does not exist on this collection instance
  • Pass input value through PHP parameter
  • Running two PHP versions on the same server (STRETCH)
  • Checking if a file has been selected for upload
  • Model not updating laravel
  • How to add a description of words from text to an array, to an array key by passing words?
  • Nginx rewrite rule not not passing variables if "/" is at the end of the url
  • Modify decimal point and thousands separator without changing the number of decimals
  • Remove PHP errors from CLI and PHPMyAdmin
  • Yii2 rest api - Url manager add parameters
  • 1-query batch update array of users using PDO
  • Keep getting error: implode(): Invalid arguments passed when updating data
  • Laravel 5.4 - Correct Validation rule for a required parameter that can be zero
  • What does this code mean: $objPHPExcel->getActiveSheet()->toArray(null, true,true,true)
  • Data not being added to mysql table but echo's the data?
  • While fetch row in PHP
  • IP long string filter
  • How to view first image in list per user as its highlight Profile
  • Insert multiple rows from array
  • PHP : How to remove a duplicate array item ONCE
  • Print the input box text as simple text instead of html tag
  • How to read a string variable in php as $_GET or $_POST?
  • MySQL query fetch array not working
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org