仅使用find方法查询MongoDB中的对象数组 [英] Querying array of objects in MongoDB using only find method

查看:310
本文介绍了仅使用find方法查询MongoDB中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB 3.4的 contacts 集合中查找以下文档:

Look the following documents in a contacts collection on MongoDB 3.4:

{
    "_id" : ObjectId("58f045526320ef24fc61fdb2"),
    "name" : "John Doe",
    "tags" : [
        {
            "name": "tagA", 
            "created_at": ISODate("2017-01-27T10:30:00Z")
        },
        {
            "name": "tagB", 
            "created_at": ISODate("2017-01-28T13:30:00Z")
        }
    ],
},
{
    "_id" : ObjectId("58f045526320ef24fc61fdb3"),
    "name" : "Johnny Doe",
    "tags" : [
        {
            "name": "tagA", 
            "created_at": ISODate("2016-12-21T19:30:00Z")
        },
        {
            "name": "tagC", 
            "created_at": ISODate("2017-01-28T13:30:00Z")
        }
    ],
}
.
. 
.

是否有任何仅使用 find 方法的查询(也没有聚合框架,也没有$ where)可以返回的查询:

Is there any query using only find method (nor aggregate framework, nor $where) that can return:

  1. 具有以下所有标签的联系人:[tagA,tagC]
  2. 没有所有这些标签的联系人:[tagC,tagD]
  3. 2017年带有所有标签的联系人

感谢进阶

推荐答案

我在要查找具有以下所有标签的联系人:[tagA, tagC],可以使用双负号查找不包含[tagA, tagC]

To find the contacts who have all the following tags: [tagA, tagC], you can use a double negative to find the documents that do NOT have elements NOT in [tagA, tagC]

db.collection.find({"tags": {"$not": {"$elemMatch": {"name": {"$nin": ["tagA", "tagC"]}}}}})

要查找没有所有这些标签的联系人,请执行以下操作:[tagC, tagD]

To find the contacts who don't have all of these tags: [tagC, tagD]

db.collection.find({"tags": {"$elemMatch": {"name": {"$nin": ["tagC", "tagD"]}}}})

尽管使用$or

db.collection.find({"tags": {"$not": {"$elemMatch": {"$or": [ 
    {"createdAt": {"$lt": ISODate("2017-01-01T00:00:00.000Z")}},
    {"createdAt": {"$gt": ISODate("2017-12-31T23:59:59.999Z")}}]}}}})

这篇关于仅使用find方法查询MongoDB中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆