计算数组中元素的数量

Count number of elements in an array

我正在创建一个应用程序,它具有从 MongoDB collection.

文档中的数组中删除元素的功能

我需要一种方法来在删除操作后数组立即变空时立即取消设置数组的字段。我需要这样做,以便我可以区分具有 non-empty 数组的文档和具有空数组的文档。

例如,现在我的 section collection 看起来像:

db.section.find({})

{ "_id" : ObjectId("57a0a38ad1c6ef24376477c5"), "sectionid" : "BTE4B", 
 "sectionname" : "BTech 4B", "year" : 4,
 "session" : 2016, "courseid" : "BTE-CS", "password" : "pm8xTE0-",
 "students" : 35, "addedon" : "2016-08-02 19:13:38", "teachers" : [ ] }

 { "_id" : ObjectId("57a0a96bd1c6ef24376477cd"), "sectionid" : "BTE4D",
 "sectionname" : "BTech 4D", "year" : 4, "session" : 2016, "courseid" :
 "BTE-CS", "password" : "sHhKr0Ov", "students" : 41, "addedon" :
 "2016-08-02 19:38:43", "teachers" : [ { "facultyid" : "CS-102",
 "subjectid" : "CS-ALGO" } ] }

我在第一个文档的 teachers 数组上使用 mgo 应用了 $pull 操作,但我需要当它变空时$unset它的一种方法。

目前,我已经设法在 Go 中创建了一个解决方法,但我想在没有任何解决方法的情况下离开。

希望我没有漏掉一些非常琐碎的东西。

谢谢!

如果数组键有零个元素,建议在教师字段上使用 findAndModify() API to do the $pull update operation first, this will return the modified document which you can then access the teachers array for checking. Once you check for array emptiness, you can then issue another update operation that calls the $unset 运算符。

mongo shell 中的典型示例如下:

change = db.section.findAndModify({
    query: { "sectionid": "BTE4D", "teachers.facultyid": "CS-102" },
    update: { "$pull": { "teachers": { "facultyid" : "CS-102" } } },
    new: true
});

printjson(change);

if (!change.teachers[0]) {
     db.section.update(
        { "_id": change._id },
        { "$unset": { "teachers": "" } }
    );
}

db.section.find({ "_id": change._id })

用 mgo 实现这个,你需要 Query.Apply method which essentially wraps the findAndModify MongoDB 命令

change := mgo.Change{
        Update: bson.M{"$pull": bson.M{"teachers": bson.M{"facultyid": "CS-102"}}},
        ReturnNew: true,
}
info, err = col.Find(M{"sectionid": "BTE4D"}).Apply(change, &doc)
fmt.Println(doc.N)

要区分空数组和非空数组,您可以使用带有 $size 运算符的查找命令。

如果您选择删除空数组,您可以使用 MongoDB findAndModify (refer the mgo documentation 发出 $pull 运算符以获得更多详细信息)它可以原子地 return 修改文档,检查数组是否为空并用另一个查询取消设置。