MongoDB $ in运算符用于存储在同一集合中的数组

时间:2016-05-10 17:22:47

标签: 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数据库:

{
    "_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
    $cursor1 = $users->find(
        array(
            "_id" => new MongoID($id),
        ),
        array(
            "friends" => 1
        )
    );
    $cursor1->next();
    $doc1 = $cursor1->current();
    $friend_arr = $doc1['friends'];
    foreach($friend_arr as $f_id){
        $cursor2 = $users->find(
            array("_id" => new MongoID($f_id)),
            array("name"=>1));
        $cursor2->next();
        $doc2 = $cursor2->current();
        echo "<div>".$doc2['name']."</div>";
    }

?>

但我知道它不能满足需要。这就是我寻求帮助的原因。

我是使用php的MongoDB新手。

非常感谢您提前寻求帮助。

1 个答案:

答案 0 :(得分:2)

好的,经过一番思考,我得到了解决方案。

$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>";
}

此代码正常运行。我在张贴之前测试了它。