Php 存储在同一集合中的数组的MongoDB$in运算符
如果我有以下模式:Php 存储在同一集合中的数组的MongoDB$in运算符,php,mongodb,Php,Mongodb,如果我有以下模式: users = { _id: MongoID name: String, email: String, password: String, online: Boolean, // Tells if user is online or not friends: Array, // Storing _ids of friends request: Array } 现在,我想得到所有在线朋友的名字,按名字排序 MongoDB数
users = {
_id: MongoID
name: String,
email: String,
password: String,
online: Boolean, // Tells if user is online or not
friends: Array, // Storing _ids of friends
request: Array
}
现在,我想得到所有在线朋友的名字,按名字排序
MongoDB数据库:
{
"_id" : ObjectId("572e43d71ccbdd080f00002b"),
"name" : "Bot 3",
"email" : "bot3@gmail.com",
"password" : "202cb962ac59075b964b07152d234b70",
"online" : false,
"friends" : [
ObjectId("572efe481ccbdd9c12000029")
],
"requests" : []
}
{
"_id" : ObjectId("572efe481ccbdd9c12000029"),
"name" : "Bot 4",
"email" : "bot4@gmail.com",
"password" : "202cb962ac59075b964b07152d234b70",
"online" : false,
"friends" : [
ObjectId("573074e81ccbddc816000029"),
ObjectId("572e43d71ccbdd080f00002b")
],
"requests" : [ ]
}
{
"_id" : ObjectId("573074e81ccbddc816000029"),
"name" : "Bot 5",
"email" : "bot5@gmail.com",
"password" : "202cb962ac59075b964b07152d234b70",
"online" : true,
"friends" : [
ObjectId("572efe481ccbdd9c12000029")
],
"requests" : [ ]
}
我想问一些问题,比如:
var arr = db.users.find({"_id": ObjectId("572efe481ccbdd9c12000029")},
{"friends": 1, "_id": 0});
db.users.find({$in: arr["friends"]}, {"name": 1, "online": 1}).sort({"name": 1});
我在上面的示例中尝试了这段php代码(甚至不符合要求):
但我知道它不能满足需要。这就是我请求帮助的原因
我不熟悉使用php的MongoDB
提前非常感谢您的帮助。好了,伙计们,我想了想才找到了解决方案
$cursor1 = $users->find(
array(
"_id" => new MongoID($id),
),
array(
"friends" => 1
)
);
$cursor1->next();
$doc1 = $cursor1->current();
$friend_arr = $doc1['friends'];
$cursor2 = $users->find(
array(
"_id"=> array(
'$in' => $friend_arr
)
),
array(
"name" => 1
)
);
$cursor2->sort(array("name"=>1));
foreach($cursor2 as $doc2){
echo "<div>".$doc2['name']."</div>";
}
$cursor1=$users->find(
排列(
“_id”=>新MongoID($id),
),
排列(
“朋友”=>1
)
);
$cursor1->next();
$doc1=$cursor1->current();
$friend_arr=$doc1['friends'];
$cursor2=$users->find(
排列(
“_id”=>数组(
“$in”=>$friend\u arr
)
),
排列(
“名称”=>1
)
);
$cursor2->排序(数组(“名称”=>1));
foreach($cursor2作为$doc2){
回显“$doc2['name']”;
}
此代码工作正常。我在发布前测试了它
$cursor1 = $users->find(
array(
"_id" => new MongoID($id),
),
array(
"friends" => 1
)
);
$cursor1->next();
$doc1 = $cursor1->current();
$friend_arr = $doc1['friends'];
$cursor2 = $users->find(
array(
"_id"=> array(
'$in' => $friend_arr
)
),
array(
"name" => 1
)
);
$cursor2->sort(array("name"=>1));
foreach($cursor2 as $doc2){
echo "<div>".$doc2['name']."</div>";
}