您好我在mongo遇到了问题。我先向您展示一个数据示例。这是我表中的记录。
{
"_id": "3691149613248",
"following": [{
"content_id": "2584833593728",
"date": "2015-08-20 12:46:55"
}, {
"content_id": "3693447751360",
"date": "2015-09-11 12:17:55"
}, {
"content_id": "2582396936896",
"date": "2015-09-12 07:04:02"
}, {
"content_id": "3697346507456",
"date": "2015-09-14 09:56:03"
}, {
"content_id": "3697755500800",
"date": "2015-09-16 10:05:51"
}, {
"content_id": "2589701320192",
"date": "2015-09-16 10:51:19"
}, {
"content_id": "2585723555136",
"date": "2015-09-16 11:40:26"
}, {
"content_id": "3695996668352",
"date": "2015-09-16 12:50:25"
}, {
"content_id": "3694290368512",
"date": "2015-09-16 12:50:33"
}, {
"content_id": "3691210127552",
"date": "2015-09-16 13:02:57"
}, {
"content_id": "3694134958464",
"date": "2015-09-16 13:06:17"
}, {
"content_id": "3697315148736",
"date": "2015-09-17 06:58:35"
}, {
"content_id": "3692104837824",
"date": "2015-09-17 12:19:12"
}, {
"content_id": "3693400309376",
"date": "2015-09-22 05:43:04"
}]
}
我想获取following
数组,条件是只提取特定记录,即前缀为content_ids
的{{1}},并在限制和偏移量中指定取值369
。 / p>
我正在使用content_id
来获取给定限制和记录的记录$slice
数组的偏移量。但是如何过滤following
以及content_id
。
我当前的查询:
$slice
这是使用 db.collectionName.find({
_id: "3691149613248"
}, {
"following": {
"$slice": [0, 10]
}
});
获取following
数组,该数组在limit&偏移。但它提取了所有content_id
,包括前缀content_id
& 258
但我只需要使用mongo查询369
前缀为content_id
。
任何人都可以帮忙吗??
答案 0 :(得分:1)
您可以将$unwind和$match与mongo aggregation结合使用,以获得预期的输出,例如:
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"
}
}
})
如果您想将skip和limit应用于上述查询,则可以轻松使用它:
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"
}
}
})
编辑:
如果您使用的PHP版本低于5.4,则查询将为:
$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);
如果您使用的PHP版本大于5.3,则只需将{
和}
括号分别替换为[
和]
。