2016-01-20 48 views
1

我想使用MongoDB/PHP以OR和AND模式從我的集合中刪除一些文檔。MongoDB/PHP - 使用OR/AND模式刪除文檔

這裏是我的SQL查詢:

DELETE FROM文檔WHERE id_document = 13 AND(IS_ACTIVE = 1或 is_pinned = 0)

它似乎沒有可能的做到這一點:

$收藏 - >刪除()

你能幫忙嗎? 謝謝:)

回答

0

查詢你追求的是

var query = { 
    "id_document": 13, 
    "$or": [ 
     { "is_active": 1 }, 
     { "is_pinned": 0 } 
    ] 
} 
db.collection.remove(query); 

下面是一些示例測試文檔中蒙戈外殼來測試這一點:

db.test.insert([ 
    { _id: 1, id_document: 13, "is_active": 1, "is_pinned": 0}, 
    { _id: 2, id_document: 13, "is_active": 0, "is_pinned": 1 }, 
    { _id: 3, id_document: 13, "is_active": 0, "is_pinned": 0 },  
    { _id: 4, id_document: 13, "is_active": 1, "is_pinned": 1 }, 
    { _id: 5, id_document: 14, "is_active": 1, "is_pinned": 1 }, 
    { _id: 6, id_document: 14, "is_active": 1, "is_pinned": 0} 
]) 

我希望刪除查詢刪除文件與_ids 1,3和4,因此輸出爲查詢

var query = { 
    "id_document": 13, 
    "$or": [ 
     { "is_active": 1 }, 
     { "is_pinned": 0 } 
    ] 
} 
db.test.remove(query); 
db.test.find(); 

將是

/* 0 */ 
{ 
    "_id" : 2, 
    "id_document" : 13, 
    "is_active" : 0, 
    "is_pinned" : 1 
} 

/* 1 */ 
{ 
    "_id" : 5, 
    "id_document" : 14, 
    "is_active" : 1, 
    "is_pinned" : 1 
} 

/* 2 */ 
{ 
    "_id" : 6, 
    "id_document" : 14, 
    "is_active" : 1, 
    "is_pinned" : 0 
} 

這個PHP實施例證明以上其使用$or操作者的概念。該$or接受表達式的數組,其中的任何一個能夠滿足上面的查詢:

<?php  

$db = $this->getMongoDbHandler(); 

$collection = $db->selectCollection('myColl'); 

$query = array(
     'id_document' => 13, 
     '$or' => array(
      array('is_active' => 1), 
      array('is_pinned' => 0), 
     )   
    ) ; 

// Remove operation 
$collection->remove($query); 

// Find remaining documents 
$cursor = $collection->find(); 
foreach ($cursor as $doc) { 
    var_dump($doc); 
} 
?> 
+0

謝謝!有用 :) – user4546765