您好,我遇到了 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
前缀为 369
并获取 的编号content_id
在limit和offset中指定。
我正在使用 $slice
为 following
数组获取给定限制和偏移量的记录。但是如何过滤 content_id
以及 $slice
。
我当前的查询:
db.collectionName.find({
_id: "3691149613248"
}, {
"following": {
"$slice": [0, 10]
}
});
这是获取 following
数组,其中 content_id
在 limit & offset 中指定。但它正在获取所有 content_id
包括前缀 258
和 369
但我只需要 content_id
和前缀 369
使用 mongo 查询。
有人能帮忙吗??
最佳答案
您可以使用 $unwind 的组合和 $match与蒙戈 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,则只需将 {
和 }
大括号替换为 [
和 ]
分别。
关于regex - 在 mongodb 的子文档数组上一起使用 $slice 和 $regex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32711053/