1

I have a collection 'news' in database as follows.

{
"_id" : ObjectId("5a6d068b0088c92a34324d8e"),
"4210003170944" : 
    {
    "date" : "20180126",
    "sectionId" : "100",
    "rank" : "1",
    "newsTitle" : "Foo",
    "oid" : "421",
    "aid" : "0003170944"
    },
"2140000800903" : 
    {
    "date" : "20180126",
    "sectionId" : "100",
    "rank" : "2",
    "newsTitle" : "Bar",
    "oid" : "214",
    "aid" : "0000800903"
    }
}

If I want to search all news with "oid" : "421", what command should I use?

I've tried

db.locations.find({ "_id" : ObjectId("5a6d068b0088c92a34324d8e")}, { oid : '421' })

but it doesn't fetch me anything.

Please correct me if I'm wrong.

1

If I want to search all news with "oid" : "421", what command should I use?

As per MongoDB BOL $match (aggregation) Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

The $match stage has the following prototype form:

{ $match: { <query> } }

So, in your case the query will be like that

   db.locations.aggregate({$match: {'4210003170944.oid': '421'}}).pretty()

Let's from starting onward i am going to show through mongo shell . First i am going to create a collection name as locations. which is a collection name in your query. Then i will insert the data , which you have provided through the code and the do the desire query with $match (aggregation).

> db.createCollection("locations")
{ "ok" : 1 }
> db.locations.insert({
... "_id" : ObjectId("5a6d068b0088c92a34324d8e"),
... "4210003170944" :
...     {
...     "date" : "20180126",
...     "sectionId" : "100",
...     "rank" : "1",
...     "newsTitle" : "Foo",
...     "oid" : "421",
...     "aid" : "0003170944"
...     },
... "2140000800903" :
...     {
...     "date" : "20180126",
...     "sectionId" : "100",
...     "rank" : "2",
...     "newsTitle" : "Bar",
...     "oid" : "214",
...     "aid" : "0000800903"
...     }
... }
... )
WriteResult({ "nInserted" : 1 })
>
> db.locations.aggregate({$match: {'4210003170944.oid': '421'}}).pretty()
{
        "_id" : ObjectId("5a6d068b0088c92a34324d8e"),
        "4210003170944" : {
                "date" : "20180126",
                "sectionId" : "100",
                "rank" : "1",
                "newsTitle" : "Foo",
                "oid" : "421",
                "aid" : "0003170944"
        },
        "2140000800903" : {
                "date" : "20180126",
                "sectionId" : "100",
                "rank" : "2",
                "newsTitle" : "Bar",
                "oid" : "214",
                "aid" : "0000800903"
        }
}

Hope this will help out to you.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.