mongodb $ not _id [英] mongodb $not _id
问题描述
我需要一种搜索方法,但不包括用户前面屏幕上已经存在的_id.例如,我有3个宠物资料,用户已经在浏览其中一个.
I need a way to search but not include an _id which is already on the screen in front of the user. For example, I have 3 pet profiles one which the user is already viewing.
在该页面上,我有一个名为我的家人"的标题.然后,我运行此搜索:
On that page I have a heading called My Family. I then run this search:
public function fetch_family($owner)
{
$collection = static::db()->mypet;
$cursor = $collection->find(array('owner' => new MongoId($owner)));
if ($cursor->count() > 0)
{
$family = array();
// iterate through the results
while( $cursor->hasNext() ) {
$family[] = ($cursor->getNext());
}
return $family;
}
}
即使我已经展示了一只宠物,它也将我家里的所有宠物都还了.因此,我想从搜索中排除一个_id.
And it returns all the pets in my family even knowing I am already showing one. So I want to exclude that one _id from the search.
我想过这样的事情.
$cursor = $collection->find(array('owner' => new MongoId($owner), '$not'=>array('_id'=>new MongoId(INSERT ID HERE))));
但是,这只是阻止了整个过程的运行.
However, that just stops the whole thing from running.
推荐答案
您需要执行 $ne
(不相等),以确保所有者正在搜索您正在查看的当前宠物.
You need to do a $ne
(not equal) to make sure the current pet you are viewing is excluded from the search by owner.
mongo
外壳中的示例:
var viewingPetId = ObjectId("515535b6760fe8735f5f6899");
var ownerId = ObjectId("515535ba760fe8735f5f689a");
db.mypet.find(
{
_id: { $ne: viewingPetId },
owner: ownerId
}
)
这篇关于mongodb $ not _id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!