MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Usando $ fatia com $ regex juntos no array subDocument no mongodb


Você pode usar a combinação de $unwind e $match com mongo agregação para obter a saída esperada 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"
    }
    }
})

Se você deseja aplicar skip e limite para a consulta acima, então você pode usá-lo facilmente 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 :

Se você estiver usando a versão do php inferior a 5.4, a 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);

Se você estiver usando a versão do PHP superior a 5.3, basta substituir { e } chaves com [ e ] respectivamente.