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


MongoDB $in operator for an array stored in the same collection

如果我有以下模式:

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的新手。

事先非常感谢你的帮助。

好吧,伙计们,经过思考,我找到了解决方案。

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

此代码工作正常。我在发布之前对它进行了测试。