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
shell 中的示例:
Example in the mongo
shell:
var viewingPetId = ObjectId("515535b6760fe8735f5f6899");
var ownerId = ObjectId("515535ba760fe8735f5f689a");
db.mypet.find(
{
_id: { $ne: viewingPetId },
owner: ownerId
}
)
这篇关于mongodb $not _id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!