mongodb $not _id

萝らか妹 提交于 2019-12-04 02:53:10

问题


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

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.

I thought something like this.

$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.


回答1:


You need to do a $ne (not equal) to make sure the current pet you are viewing is excluded from the search by owner.

Example in the mongo shell:

var viewingPetId = ObjectId("515535b6760fe8735f5f6899");
var ownerId = ObjectId("515535ba760fe8735f5f689a");

db.mypet.find(
    {
        _id: { $ne: viewingPetId },
        owner: ownerId
    }
)



回答2:


Use $ne as (notice no need to use ObjectId(), string will autocast to ObjectId):

db.organizations.find({"_id" : {$ne:"563c50e05cdb2be30391e873"}})


来源:https://stackoverflow.com/questions/15020261/mongodb-not-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!