sql >> Base de Datos >  >> NoSQL >> MongoDB

Uso de $slice con $regex juntos en la matriz de subdocumentos en mongodb

Puede usar una combinación de $unwind y $match con mongo agregación para obtener el resultado esperado como:

db.collection.aggregate({
    $match: {
    "_id": "3691149613248"  // you can skip this condition if not required
    }
}, {
    $unwind: "$following"
}, {
    $match: {
    "following.content_id": {
        $regex: /^369/
    }
    }
}, {
    $group: {
    _id: "$_id",
    "following": {
        $push: "$following"
    }
    }
})

Si desea aplicar skip y limit a la consulta anterior, entonces puede usarla fácilmente como:

db.collection.aggregate({
    $match: {
    "_id": "3691149613248" //use this if you want to filter out by _id
    }
}, {
    $unwind: "$following"
}, {
    $match: {
    "following.content_id": {
        $regex: /^369/
    }
    }
}, {
    $skip: 4  // you can set offset here
}, {
    $limit: 3 // you can set limit here
}, {
    $group: {
    _id: "$_id",
    "following": {
        $push: "$following"
    }
    }
})

EDITAR :

Si está utilizando una versión de php inferior a 5.4, la consulta será como:

$search = "369";
$criteria = array(array("$match" => array("_id" => "3691149613248")),
    array("$unwind" => "$following"),
    array("$match" => array("following.content_id" => array("$regex" => new MongoRegex("/^$search/")))),
    array("$skip" => 4), array("$limit" => 3),
    array("$group" => array("_id" => "$_id", "following" => array("$push" => "$following"))));
$collection - > aggregate($criteria);

Si está utilizando una versión de PHP superior a 5.3, simplemente reemplace { y } llaves con [ y ] respectivamente.