1, 某字段的值,在集合collection A中存在,在集合collection B中不存在,即集合A和B的差集
db.getCollection('CollctionA')
.aggregate(
[
{
$lookup: {
from: "CollctionB",
localField: 'CollctionA_Id',
foreignField: 'CollctionB_id',
as: "CollctionA_B_Data"
}
},
{ $unwind: { path: '$CollctionA_B_Data', preserveNullAndEmptyArrays: true } },
{
$project: {
_id: '$_id',
CollctionB_id: '$CollctionA_B_Data.CollctionB_id',
CollctionA_Id: '$CollctionA_Id'
}
},
// {
// $project: {
// temp: {
// _id: '$_id',
CollctionB_id: '$CollctionA_B_Data.CollctionB_id',
CollctionA_Id: '$CollctionA_Id'
// }
// }
// },
// {
// $group: {
// _id: null,
// total: { $sum: 1 },
// data: { $push: "$temp" }
// }
// }
{
$match: {
CollctionB_id: { $eq: null }
}
}
])
2. Mongodb中对collection中的字段做模糊查询,并且不区分大小写
db.getCollection('CollectionA').aggregate([
{
"$match":{
"filed_a": { $regex: "BCD-12" , $options: 'i'}
}
}
])
// Sample data
// "filed_a": "ABCD-1234"
// "filed_a": "AbcD-12"
// 模糊查询的同时,还可以做 或操作
db.CollectionA.find({"typeA": {"$regex": "BCD|EFG"}});
3. Mongodb中对collection中的某一个字段,取其无重复的值,即distinct
db.CollectionA.distinct( "Type" )
4. Mongodb中,查看某一个字段是否在一个collection中存在
db.CollectionB.find({country:{$exists:true}});
5. Mongodb中,查看一个collection中的所有fields, Find all field names in MongoDb
// I ran this Javascript at the Mongo shell to get all the field names.
var arrayOfFieldNames = [];
var items = db.CollectionA.find();
while(items.hasNext()) {
item = items.next();
for(var index in item) {
arrayOfFieldNames[index] = index;
}
}
for (var index in arrayOfFieldNames) {
print(index);
}
var data = db.CollectionA.findOne();
for (var key in data) { print (key) ; }
6. 查询集合中重复的数据
{ "_id" : 1, "userid" : "aa1" },
{ "_id" : 2, "userid" : "aa2" },
{ "_id" : 3, "userid" : "aa2" },
{ "_id" : 4, "userid" : "aa2" }
db.getCollection('users').aggregate([
{ $group: { _id : '$userid', count: { $sum : 1 } } },
{ $match: { count: { $gt : 1} } }
])