MongoDB中的$ pull运算符

时间:2018-09-28 11:45:29

标签: mongodb pull

    func fatchImagesfromAlbum() {

        DispatchQueue.global(qos: .background).async {
        self.photoAssets = self.fetchResult as! PHFetchResult<AnyObject>

        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)


        self.photoAssets = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions) as! PHFetchResult<AnyObject>

        for i in 0..<self.photoAssets.count{
            autoreleasepool {

                let asset = self.photoAssets.object(at: i)

                let imageSize = CGSize(width: asset.pixelWidth,
                                       height: asset.pixelHeight)

                let options = PHImageRequestOptions()
                options.deliveryMode = .fastFormat
                options.isSynchronous = true
                options.isNetworkAccessAllowed = true


                self.imageManager.requestImage(for: asset as! PHAsset, targetSize: imageSize, contentMode: .aspectFill, options: options, resultHandler: { (image, info) -> Void in

                    if image != nil {
                    let image1 = image as! UIImage
                    let imageUrl          = info!["PHImageFileURLKey"] as? NSURL
                    let imageName         = imageUrl?.lastPathComponent
                    let urlString: String = imageUrl!.path!
                    let theFileName = (urlString as NSString).lastPathComponent
                    self.imageName.append("\(theFileName)")
                    self.imagePath.append("\(urlString)")

                    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
                    let localPath         = photoURL.appendingPathComponent(imageName!)
                    DispatchQueue.global(qos: .background).async {
                        if !FileManager.default.fileExists(atPath: localPath!.path) {
                            do {
                                try UIImageJPEGRepresentation(image1, 0.1)?.write(to: localPath!)
                                print("file saved")
                            }catch {
                                print("error saving file")
                            }
                        }
                        else {
                            print("file already exists")
                        }
                    }
                }
              })
                DispatchQueue.main.async
                    {
                        self.collectionView.reloadData()
                }
            }
        }
        self.hudHide()
    }
        PHPhotoLibrary.shared().register(self)

    if fetchResult == nil {
        let allPhotosOptions = PHFetchOptions()
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        fetchResult = PHAsset.fetchAssets(with: allPhotosOptions)
    }
       }

上述架构是“计划”架构 我必须编写一个查询来删除“活动”数组中的活动。最佳的解决方案是什么?而我将如何使用$ pull来实现这一点 这是我的解决方案,但是它将删除完整的分组数组

{
    "_id" : ObjectId("5badfada90fd543fd8aa7f96"),
    "__v" : 0,
    "deleted" : false,
    "groups" : [ 
        {
            "group" : "grp",
            "_id" : ObjectId("5bae09a601123357e58b66a2"),
            "activities" : [ 
                ObjectId("5bae09a601123357e58b66a3"), 
                ObjectId("5bae10de01123357e58b66a6")
            ]
        }, 
        {
            "group" : "123",
            "_id" : ObjectId("5bae0f1001123357e58b66a4"),
            "activities" : [ 
                ObjectId("5bae0f1001123357e58b66a5")
            ]
        }
    ],
    "nextActivityId" : 22,
    "name" : "test",
    "year" : "1",
    "status" : "2",
    "vision" : ObjectId("5bab2f4872acf42a81c124d0")
}

计划ID为:“ _ id”:ObjectId(“ 5badfada90fd543fd8aa7f96”), 例如的活动ID:ObjectId(“ 5bae09a601123357e58b66a3”)

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要使用位置$更新操作符。

db.Plan.update(
    { "_id" : PLAN ID }, 
    { "$pull": { "groups.$.activities": ACTIVITY ID } } 
)

答案 1 :(得分:0)

您可以尝试一下,

    db.Plan.update({ _id: ObjectId("5badfada90fd543fd8aa7f96"),"groups.activities":{$in:[ ObjectId("5bae09a601123357e58b66a3") ]}},
{ $pull: { "groups.$.activities": ObjectId("5bae09a601123357e58b66a3") }  });

仅使用$更新对象时,位置运算符未从查询警告中找到所需的匹配项。